相关疑难解决方法(0)

为什么不等待Task.WhenAll抛出AggregateException?

在这段代码中:

private async void button1_Click(object sender, EventArgs e) {
    try {
        await Task.WhenAll(DoLongThingAsyncEx1(), DoLongThingAsyncEx2());
    }
    catch (Exception ex) {
        // Expect AggregateException, but got InvalidTimeZoneException
    }
}

Task DoLongThingAsyncEx1() {
    return Task.Run(() => { throw new InvalidTimeZoneException(); });
}

Task DoLongThingAsyncEx2() {
    return Task.Run(() => { throw new InvalidOperation();});
}
Run Code Online (Sandbox Code Playgroud)

我期望WhenAll创建并抛出一个AggregateException,因为至少有一个等待抛出异常的任务.相反,我正在收回其中一个任务抛出的单个异常.

难道WhenAll不总是创造AggregateException

.net asynchronous exception tap

83
推荐指数
6
解决办法
3万
查看次数

为什么Task.WhenAny没有抛出预期的TimeoutException?

请遵守以下简单的代码:

class Program
{
    static void Main()
    {
        var sw = new Stopwatch();
        sw.Start();
        try
        {
            Task.WhenAny(RunAsync()).GetAwaiter().GetResult();
        }
        catch (TimeoutException)
        {
            Console.WriteLine("Timed out");
        }
        Console.WriteLine("Elapsed: " + sw.Elapsed);
        Console.WriteLine("Press Enter to exit");
        Console.ReadLine();
    }

    private static async Task RunAsync()
    {
        await Observable.StartAsync(async ct =>
        {
            for (int i = 0; i < 10; ++i)
            {
                await Task.Delay(500, ct);
                Console.WriteLine("Inside " + i);
            }
            return Unit.Default;
        }).Timeout(TimeSpan.FromMilliseconds(1000));
    }
}
Run Code Online (Sandbox Code Playgroud)

运行它输出:

Inside 0
Inside 1
Elapsed: 00:00:01.1723818
Press Enter to exit
Run Code Online (Sandbox Code Playgroud)

注意,没有 …

.net c# task-parallel-library system.reactive async-await

12
推荐指数
1
解决办法
3760
查看次数