为什么unawaited异步方法不抛出异常?

编程入门 行业动态 更新时间:2024-10-07 00:16:33
本文介绍了为什么unawaited异步方法不抛出异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我认为异步方法应该像普通方法一样,直到达到等待。

为什么不抛出异常?

有没有办法在等待之前抛出异常?

使用系统; 使用System.Threading.Tasks; public class Test { public static void Main() { var t = new Test(); t.Helper(); } public async Task Helper() { throw new Exception(); } }

解决方案

根据设计,将 async 方法抛出的异常存储在返回的任务中。要得到你的例外,你可以:

  • await 任务: code>等待t.Helper();
  • 等待任务: t.Helper()。Wait();
  • 检查任务的异常属性 after 任务已完成: var task = t.Helper();日志(task.Exception);
  • 向处理异常的任务添加一个延续: t.Helper()。ContinueWith t => Log(t.Exception),TaskContinuationOptions.OnlyOnFaulted);
  • 你最好的选择是第一个。只需等待任务并处理异常(除非有特定的原因你不能这样做)。更多 .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异步方法不抛出异常?

    本文发布于:2023-11-05 10:29:23,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1560589.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:抛出   异常   方法   unawaited

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!