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

查看:259
本文介绍了为什么unawaited异步方法不抛出异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为异步方法都应该表现得像个普通的方法,直到他们来到了一个计谋。

为什么这不会抛出异常?

有没有办法让抛出的异常不必等待?

 使用系统;
使用System.Threading.Tasks;

公共类测试
{
    公共静态无效的主要()
    {
        变种T =新的测试();
        t.Helper();
    }

    公共异步任务助手()
    {
        抛出新的异常();
    }
}
 

解决方案

抛出内部的例外异步的方法是,在设计上,存储返回的任务中。为了得到你的手异常,您可以:

  1. 计谋任务:等待t.Helper();
  2. 等待任务: t.Helper()等待();
  3. 检查任务的异常属性的的任务已经完成: VAR任务= t.Helper();日志(task.Exception);
  4. 添加延续到任务处理异常: 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:

  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天全站免登陆