Ensuring primary thread waits for all Tasks to complete

前端 未结 1 1272
小鲜肉
小鲜肉 2021-01-23 06:09

I\'m writing a C# console app and having an issue where the primary thread closes before all the spawned off Tasks have a chance to complete. General program flow looks like thi

相关标签:
1条回答
  • 2021-01-23 06:46

    You can put all of the tasks you get into a List<Task> instead of just creating them and tossing them, and then use the Task.WaitAll() to wait for completion:

    var tasks = new List<Task>();
    
    foreach (KeyValuePair<string, List<string>> entry in productDictionary) {
        string writePath = String.Format(@"{0}\{1}-{2}.txt", directoryPath, hour, entry.Key);
        List<string> quotes = entry.Value;
    
        // add task to list
        tasks.Add(Task.Factory.StartNew(() => WriteProductFile(writePath, quotes)));
    }
    
    // now wait for all tasks to finish, you'd also want to handle  exceptions of course.
    Task.WaitAll(tasks.ToArray());
    

    There are many variations of WaitAll(), you could wait indefinitely (as above), or wait for a TimeSpan and if time-out then print a progress message and wait again, etc...

    0 讨论(0)
提交回复
热议问题