Task.WaitAll and Exceptions

后端 未结 3 1318
粉色の甜心
粉色の甜心 2020-12-23 21:30

I have a problem with exception handling and parallel tasks.

The code shown below starts 2 tasks and waits for them to finish. My problem is, that in case a task thr

3条回答
  •  感情败类
    2020-12-23 22:04

    Here's how I solved the problem, as alluded to in the comments on my answer/question (above):

    The caller catches any exceptions raised by the tasks being coordinated by the barrier, and signals the other tasks with a forced cancellation:

    CancellationTokenSource cancelSignal = new CancellationTokenSource();
    try
    {
        // do work
        List workerTasks = new List();
        foreach (Worker w in someArray)
        {
            workerTasks.Add(w.DoAsyncWork(cancelSignal.Token);
        }
        while (!Task.WaitAll(workerTasks.ToArray(), 100, cancelSignal.Token)) ;
    
     }
     catch (Exception)
     {
         cancelSignal.Cancel();
         throw;
     }
    

提交回复
热议问题