WaitAll vs WaitAny

I'm a little confused for WaitAllu WaitAny. I try to get an exception, but when I do WaitAll, it returns an exception, but when use WaitAnyreturns nothing. And it is necessary that any of the completed work be carried out. They are any replacement WaitAny(). WaitAlland WhenAllthey are different from each other because I don’t want everything to be done. how

try
{
    int i = 0;
    Task t1 = Task.Factory.StartNew(() =>
        {
            i = 2 * 4;
        });

    Task<int> t2 = Task.Factory.StartNew(() =>
        {
            int a = 0;
            int b = 100 / a;
            return 0;
        });

    Task[] tasks = new Task[] { t1, t2 };
    Task.WaitAny(tasks);
    //Task.WaitAll(tasks);// Working

}
catch (AggregateException ae)
{
    var message = ae.InnerException.Message;
    Console.WriteLine(message);
}
Console.ReadLine();
+4
source share
3 answers

Unobserved Exception, Task Parallel Library (TPL) ThreadPool :

UnobservedTaskException, ( , ), . , , , , .

, WaitAny(), - , .

+4

, - , : Asycnronous Pattern .

public static Task<Task[]> WhenAllOrFirstException(params Task[] tasks)
{
    var countdownEvent = new CountdownEvent(tasks.Length);
    var completer = new TaskCompletionSource<Task[]>();

    Action<Task> onCompletion = completed =>
        {
            if (completed.IsFaulted && completed.Exception != null)
            {
                completer.TrySetException(completed.Exception.InnerExceptions);
            }

            if(countdownEvent.Signal() && !completer.Task.IsCompleted)
            {
                completer.TrySetResult(tasks);
            }
        };

    foreach(var task in tasks)
    {
        task.ContinueWith(onCompletion)
    }

    return completer.Task;
}
+3

WaitAny , , . WaitAny , ( t2), .

WaitAny - descriobed Task.WhenAny Unobserved Exceptions

0

Source: https://habr.com/ru/post/1672460/


All Articles