我对 WaitAllWaitAny 有点困惑。我正在尝试获取异常,但是当我执行 WaitAll 时它返回异常但是当使用 WaitAny 时什么都不返回。而且必要的是,如果任何任务完成工作完成。是否有任何替换 WaitAny()WaitAllWhenAll 不同,因为我不想让所有任务都完成。喜欢

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();

最佳答案

也许你想要这样的东西。请注意,这使用 Task-based Asynchronous 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;
}

关于c# - WaitAll 与 WaitAny,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42833400/

10-10 21:31