本文介绍了为什么unawaited异步方法不抛出异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我认为异步方法应该像普通方法一样,直到达到等待。 await 任务: code>等待t.Helper(); 等待任务: t.Helper()。Wait(); 检查任务的异常属性 after 任务已完成: var task = t.Helper();日志(task.Exception); 向处理异常的任务添加一个延续: t.Helper()。ContinueWith t => Log(t.Exception),TaskContinuationOptions.OnlyOnFaulted); 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);
为什么不抛出异常?
有没有办法在等待之前抛出异常?
使用系统; 使用System.Threading.Tasks; public class Test { public static void Main() { var t = new Test(); t.Helper(); } public async Task Helper() { throw new Exception(); } }解决方案
根据设计,将 async 方法抛出的异常存储在返回的任务中。要得到你的例外,你可以:
你最好的选择是第一个。只需等待任务并处理异常(除非有特定的原因你不能这样做)。更多 .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:
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异步方法不抛出异常?
发布评论