为什么unawaited异步方法不抛出异常? [英] Why do unawaited async methods not throw exceptions?

查看:167
本文介绍了为什么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 方法抛出的异常存储在返回的任务中。要得到你的例外,你可以:


  1. await 任务: code>等待t.Helper();

  2. 等待任务: t.Helper()。Wait();

  3. 检查任务的异常属性 after 任务已完成: var task = t.Helper();日志(task.Exception);

  4. 向处理异常的任务添加一个延续: 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:

  1. await the task: await t.Helper();
  2. Wait the task: t.Helper().Wait();
  3. Check the task's Exception property after the task has been completed: var task = t.Helper(); Log(task.Exception);
  4. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆