【发布时间】:2018-03-28 18:51:30
【问题描述】:
以下程序我想捕获我认为在访问 t.Result 时应该发生的异常
class Program
{
static void Main(string[] args)
{
Task.Run(async () => await Test()).Wait();
Console.ReadKey();
}
private static async Task Test()
{
var t1 = Task.Run<int>(() => { throw new Exception("1"); return 1; });
var tasks = new[]
{
//t1.ContinueWith(t => {
// var y = t.Result + 1;
// }),
//t1.ContinueWith(t => {
// var y = t.Result + 1;
// })
t1.ContinueWith(async t =>
{
var y = t.Result + 1;
await Task.Delay(100);
}),
t1.ContinueWith(async t =>
{
var y = t.Result + 1;
await Task.Delay(100);
}),
};
try
{
await Task.WhenAll(tasks);
}
catch (Exception ex)
{
Console.WriteLine("Exception caught");
}
}
}
但如果我使用异步委托,则不会捕获异常。两个任务都有错误,但它们的异常为空。
问题
- 有什么诀窍,我在哪里可以阅读更多详细信息?
- 如果我在某些方面失去了等待,我能否确保在 Task.WhenAll 返回后继续完成?
【问题讨论】:
标签: .net task-parallel-library