How to determine when all task is completed

后端 未结 4 1994
清歌不尽
清歌不尽 2021-02-14 11:50

here is sample code for starting multiple task

Task.Factory.StartNew(() =>
        {
            //foreach (KeyValuePair entry in dicLis         


        
相关标签:
4条回答
  • 2021-02-14 12:26

    You can use the WaitAll(). Example :

    Func<bool> DummyMethod = () =>{
        // When ready, send back complete!
        return true;
    };
    
    // Create list of tasks
    System.Threading.Tasks.Task<bool>[] tasks = new System.Threading.Tasks.Task<bool>[2];
    
    // First task
    var firstTask = System.Threading.Tasks.Task.Factory.StartNew(() => DummyMethod(), TaskCreationOptions.LongRunning);
    tasks[0] = firstTask;
    
    // Second task
    var secondTask = System.Threading.Tasks.Task.Factory.StartNew(() => DummyMethod(), TaskCreationOptions.LongRunning);
    tasks[1] = secondTask;
    
    // Launch all
    System.Threading.Tasks.Task.WaitAll(tasks);
    
    0 讨论(0)
  • 2021-02-14 12:28

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

    You can use Task.WaitAll. This call will block current thread until all tasks are finished.

    Side note: you seem to be using Task, Parallel and Thread.SpinWait, which makes your code complex. I would spend a bit of time analysing if that complexity is really necessary.

    0 讨论(0)
  • 2021-02-14 12:43

    Another solution:

    After the completion of all the operation inside Parallel.For(...) it return an onject of ParallelLoopResult, Documentation:

    For returns a System.Threading.Tasks.ParallelLoopResult object when all threads have completed. This return value is useful when you are stopping or breaking loop iteration manually, because the ParallelLoopResult stores information such as the last iteration that ran to completion. If one or more exceptions occur on one of the threads, a System.AggregateException will be thrown.

    The ParallelLoopResult class has a IsCompleted property that is set to false when a Stop() of Break() method has been executed.

    Example:

    ParallelLoopResult result = Parallel.For(...);
    
    if (result.IsCompleted)
    {
        //Start another task
    }
    

    Note that it advised to use it only when breaking or stoping the loop manually (otherwise just use WaitAll, WhenAll etc).

    0 讨论(0)
  • 2021-02-14 12:46

    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.
    0 讨论(0)
提交回复
热议问题