【发布时间】:2014-05-08 15:41:28
【问题描述】:
async Task 方法抛出的异常的 normal behavior 是保持休眠状态,直到它们稍后被观察到,或者直到任务被垃圾收集。
我能想到我可能想立即扔掉的情况。这是一个例子:
public static async Task TestExAsync(string filename)
{
// the file is missing, but it may be there again
// when the exception gets observed 5 seconds later,
// hard to debug
if (!System.IO.File.Exists(filename))
throw new System.IO.FileNotFoundException(filename);
await Task.Delay(1000);
}
public static void Main()
{
var task = TestExAsync("filename");
try
{
Thread.Sleep(5000); // do other work
task.Wait(); // wait and observe
}
catch (AggregateException ex)
{
Console.WriteLine(new { ex.InnerException.Message, task.IsCanceled });
}
Console.ReadLine();
}
我可以使用async void 来解决这个问题,它会立即抛出:
// disable the "use await" warning
#pragma warning disable 1998
public static async void ThrowNow(Exception ex)
{
throw ex;
}
#pragma warning restore 1998
public static async Task TestExAsync(string filename)
{
if (!System.IO.File.Exists(filename))
ThrowNow(new System.IO.FileNotFoundException(filename));
await Task.Delay(1000);
}
现在我可以使用Dispatcher.UnhandledException 或AppDomain.CurrentDomain.UnhandledException 立即处理此异常,至少可以立即引起用户注意。
对于这种情况还有其他选择吗?这可能是一个人为的问题吗?
【问题讨论】:
-
我投票赞成一个人为的问题。 :) 理想情况下,异步代码将是响应式的,因此任务出错和观察到该任务出错之间的时间应该很短。
-
投票确认,tks :)
标签: c# .net task-parallel-library async-await