为什么unawaited异步方法不抛出异常? [英] Why do unawaited async methods not throw exceptions?
问题描述
我认为异步方法都应该表现得像个普通的方法,直到他们来到了一个计谋。
为什么这不会抛出异常?
有没有办法让抛出的异常不必等待?
使用系统;
使用System.Threading.Tasks;
公共类测试
{
公共静态无效的主要()
{
变种T =新的测试();
t.Helper();
}
公共异步任务助手()
{
抛出新的异常();
}
}
抛出内部的例外异步
的方法是,在设计上,存储返回的任务中。为了得到你的手异常,您可以:
-
计谋
任务:等待t.Helper();
-
等待
任务:t.Helper()等待();
- 检查任务的
异常
属性的在的任务已经完成:VAR任务= t.Helper();日志(task.Exception);
- 添加延续到任务处理异常:
t.Helper()ContinueWith(T =>日志(t.Exception),TaskContinuationOptions.OnlyOnFaulted);
您最好的选择是第一位的。简单地等待
任务和处理异常(除非有特殊原因,你不能这样做)。更多<一href="http://blogs.msdn.com/b/pfxteam/archive/2011/09/28/task-exception-handling-in-net-4-5.aspx">Task异常处理在.NET 4.5
I thought that async methods were supposed to behave like normal methods until they arrived at an await.
Why does this not throw an exception?
Is there a way to have the exception thrown without awaiting?
using System;
using System.Threading.Tasks;
public class Test
{
public static void Main()
{
var t = new Test();
t.Helper();
}
public async Task Helper()
{
throw new Exception();
}
}
An exception thrown inside an async
method is, by design, stored inside the returned task. To get your hands on the exception you can:
await
the task:await t.Helper();
Wait
the task:t.Helper().Wait();
- Check the task's
Exception
property after the task has been completed:var task = t.Helper(); Log(task.Exception);
- Add a continuation to that task that handles the exception:
t.Helper().ContinueWith(t => Log(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
Your best option is the first one. Simply await
the task and handle the exception (unless there's a specific reason you can't do that). More in Task Exception Handling in .NET 4.5
这篇关于为什么unawaited异步方法不抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!