gpt4 book ai didi

c# - 在异步方法中捕获异常

转载 作者:行者123 更新时间:2023-11-30 20:36:30 27 4
gpt4 key购买 nike

我正在尝试更加熟悉异步/等待编程和异常处理。

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!");
}

我期待Exception 得到妥善处理,但代码执行停止了,我得到了

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

但是当我继续执行代码时,Exception 实际上被捕获(并且消息显示到 Console)。

我应该如何在不中断代码执行的情况下捕获Exception

最佳答案

首先,你的异常被处理了。我相信您看到代码停止执行并显示错误,因为您有 Break When Thrown on 异常(exception)情况。检查您的异常窗口 ( Debug -> Windows -> Exception Settings )。

当您使用 void 的返回类型时在 async 上方法,您无法从该方法中获取任何类型的信息 - 它是一劳永逸的。除了在特定情况下,这是不好的做法。始终让您的异步方法返回 TaskTask<T> :

private static async Task TestAsyncException()

现在,您的 main 方法可以监听任务了:

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

通常,您可以使用 await在此处展开​​任务,但在应用程序入口点不允许这样做。

关于c# - 在异步方法中捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36865572/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com