Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine when all task is completed

here is sample code for starting multiple task

Task.Factory.StartNew(() =>
        {
            //foreach (KeyValuePair<string, string> entry in dicList)

            Parallel.ForEach(dicList,
                entry =>
                {

                    //create and add the Progress in UI thread
                    var ucProgress = (Progress)fpPanel.Invoke(createProgress, entry);

                    //execute ucProgress.Process(); in non-UI thread in parallel. 
                    //the .Process(); must update UI by using *Invoke
                    ucProgress.Process();

                    System.Threading.Thread.SpinWait(5000000);
                });
        });
.ContinueWith(task => 
  {
      //to handle exceptions use task.Exception member

      var progressBar = (ProgressBar)task.AsyncState;
      if (!task.IsCancelled)
      {
          //hide progress bar here and reset pb.Value = 0
      }
  }, 
  TaskScheduler.FromCurrentSynchronizationContext() //update UI from UI thread
  );

when we start multiple task using Task.Factory.StartNew() then we can use .ContinueWith() block to determine when each task finish. i mean ContinueWith block fire once for each task completion. so i just want to know is there any mechanism in TPL library. if i start 10 task using Task.Factory.StartNew() so how do i notify after when 10 task will be finish. please give some insight with sample code.

like image 627
Thomas Avatar asked Jun 10 '13 10:06

Thomas


People also ask

Which of the below statement creates a task that will complete when all of the supplied tasks have completed?

WhenAll(IEnumerable<Task>) Creates a task that will complete when all of the Task objects in an enumerable collection have completed.

What does WhenAll return?

public static Task WhenAll (params Task[] tasks); Task. WhenAll creates a task that will complete when all of the supplied tasks have been completed. It's pretty straightforward what this method does, it simply receives a list of Tasks and returns a Task when all of the received Tasks completes.


1 Answers

if i start 10 task using Task.Factory.StartNew() so how do i notify after when 10 task will be finish

Three options:

  • The blocking Task.WaitAll call, which only returns when all the given tasks have completed
  • The async Task.WhenAll call, which returns a task which completes when all the given tasks have completed. (Introduced in .NET 4.5.)
  • TaskFactory.ContinueWhenAll, which adds a continuation task which will run when all the given tasks have completed.
like image 182
Jon Skeet Avatar answered Sep 29 '22 10:09

Jon Skeet