最近犯了个低级错误,在编写异步方法时,于内部做了throw new Exception()操作,导致上层线程直接死锁。
一般规范来讲,在await方法内部,不要主动抛出异常,这样做会让子线程意外终止,代码无法继续运行。
如果想要捕获一个async方法的异常,可以用如下方式:
private async Task<bool> DoSomething()
{
throw new Exception("ops!")
}
//于调用上述方法的位置
var task = PollingLoop();
task.ContinueWith(t =>
{
//打印日志等操作
Console.WriteLine(t.Exception.Message);
},TaskContinuationOptions.OnlyOnFaulted);
这样就可以在线程发生异常时正确的捕获到异常而不会导致死锁了。