在异步方法中捕获异常 [英] Catching an exception in an async method

查看:146
本文介绍了在异步方法中捕获异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  static void Main(string [] args)
{
TestAsyncException();
}

private static async void TestAsyncException()
{
try
{
var result = await Task.Factory.StartNew(( )=> DoSomething());
//做一些结果
}
catch(异常e)
{
Console.WriteLine(e.Message);
}
}

private static int DoSomething()
{
抛出新异常(异常被抛出!
}

我期待异常要正常处理,而代码执行停止,我得到


类型为System.Exception的异常发生在..但是在用户代码中没有处理
。但是,当我继续执行代码时, Exception 实际上被捕获(


并且该消息显示给控制台)。



我应该如何抓住

解决方案

首先,你的异常被处理。我相信你看到代码停止执行并显示错误,因为你有 Break Throwwn 打开异常。检查您的异常窗口(调试 - > Windows - >异常设置)。



async 方法中的类型 void ,您无法从方法中获取任何类型的信息 - 它是火和忘记除了具体情况外,这是不好的做法。始终使用异步方法返回任务任务< T>

 私有静态异步任务TestAsyncException()

现在,您的主要方法可以听取任务:

  static void Main(string [] args)
{
TestAsyncException()。Wait(); //或任何你想要做的任务
Console.Read();
}

通常,您可以使用 await 在这里解开任务,但是在应用程序入口点不允许这样做。


I am trying to get more familiar with async/await programming and exception handling.

static void Main(string[] args)
{
   TestAsyncException();
}

private static async void TestAsyncException()
{
    try
    {
        var result = await Task.Factory.StartNew(() => DoSomething());
        //do something with the result
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
    }
}

private static int DoSomething()
{
    throw new Exception("Exception was thrown!");
}

I am expecting the Exception to be handled gracefully but instead the code execution stops and I get

An exception of type 'System.Exception' occurred in .. but was not handled in user code.

But then when I continue executing the code the Exception actually gets caught (and the message is displayed to the Console).

How am I supposed to catch the Exception without breaking the execution of my code?

解决方案

First of all, your exception is handled. I believe you are seeing the code stop execution and display the error because you have Break When Thrown on for exceptions. Check your Exception Window (Debug -> Windows -> Exception Settings).

When you use a return type of void on an async method, you lack the ability to get any sort of information back from the method - it's fire and forget. Except in specific situations, this is bad practice. Always have your async methods return a Task or Task<T>:

private static async Task TestAsyncException()

Now, your main method can listen to the task:

static void Main(string[] args)
{
    TestAsyncException().Wait(); // or whatever you want to do with the task
    Console.Read();
}

Normally, you could use await to unwrap the task here, but that's not allowed in the application entry point.

这篇关于在异步方法中捕获异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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