Task completion

I have a loop that creates several tasks, as shown below. How to update the screen (add a new line to the text box with some data) as each task completes?

How to determine when all tasks are completed?

C # code

for (int i = 0; i < int.Parse(radTextBoxFloodRequests.Text); i++) { int x = i; // Create a task and supply a user delegate by using a lambda expression. var taskA = new Task(() => TaskRequest(int.Parse(radTextBoxFirstNumber.Text), int.Parse(radTextBoxSecondNumber.Text), int.Parse(radTextBoxFloodDelay.Text), x)); // Start the task. taskA.Start(); } private void TaskRequest(int number1, int number2, int delay, int count) { // Some long running method } 
+6
source share
4 answers

You can use ContinueWith() :

"Creates a continuation that runs asynchronously when the target completes." - MSDN

 Task t = new Task(() => Console.WriteLine("")).ContinueWith(task => Console.Writeline("Continue With"), TaskScheduler.FromCurrentSynchronizationContext()); 
+13
source

I recommend you use a combination of three simple designs:

  • simple int numActiveTasks , which increases with InterlockedIncrement(ref numActiveTasks) when creating a task, i.e. immediately before taskA.Start() and is reduced using InterlockedDecrement(ref numActiveTasks) at the end of the task, i.e. at the end of the TaskRequest(...) function
  • a ManualResetEvent , that is, reset before the task ManualResetEvent and is signaled at the end of the task after the counter decrement
  • the thread that WaitOne() on ManualResetEvent then reads numActiveTasks

It gives you

  • Failure to complete one task
  • notification of all completed tasks (numActiveTasks <= 0)

The main advantage of this is that you have sovereignty about which thread this notification occurs in.

+1
source

Are you looking for Parallel.ForEach() ?

  [Test] public void ParallelTasks() { var strings = new List<string> {"task1", "task2", "task3"}; Parallel.ForEach(strings, str => Console.WriteLine(str + "is done")); // All your parallel tasks are executed now } 
+1
source

Turning to user 12345678, answer, you can do something like below.

  private void RunTasks() { Dictionary<string, string> dict = new Dictionary<string, string>(); List<Task> tasks = new List<Task>(); foreach (KeyValuePair<string,string> kvp in dict) { Console.WriteLine("Executing task " + kvp.Key + " ..."); Task t = new Task(() => MyMethod(kvp.Key, kvp.Value)); tasks.Add(t); t.Start(); t.ContinueWith(task => Console.WriteLine(kvp.Key + " completed")); } Console.WriteLine("Waiting tasks to complete..."); Task.WaitAll(tasks.ToArray()); Console.WriteLine("All tasks completed..."); } private void MyMethod(string arg1, string arg2) { } 
+1
source

All Articles