How to determine when all task is completed

后端 未结 4 1987
清歌不尽
清歌不尽 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 DummyMethod = () =>{
        // When ready, send back complete!
        return true;
    };
    
    // Create list of tasks
    System.Threading.Tasks.Task[] tasks = new System.Threading.Tasks.Task[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);
    

提交回复
热议问题