gpt4 book ai didi

c# - 异步/等待抛出未处理的异常

转载 作者:太空宇宙 更新时间:2023-11-03 23:04:28 24 4
gpt4 key购买 nike

我正在尝试从任务中实现异常处理,但我似乎无法正确处理。我已经找到了该模式的一些示例,但无论我尝试什么,我似乎总是从任务本身中获得未处理的异常。我一定是错过了什么,但我看不到什么。非常感谢任何帮助。

我尝试了一个在 MSDN 上找到的示例,但它对我不起作用:

https://msdn.microsoft.com/en-us/library/dd997415(v=vs.110).aspx

我遵循了这个问题的答案,但是当我在 Visual Studio 中运行修复程序时,它仍然提示未处理的异常:

ContinueWith TaskContinuationOptions.OnlyOnFaulted does not seem to catch an exception thrown from a started task

这是我最初写的代码:

static void Main(string[] args)
{
TestAsync().ContinueWith(t =>
{
Console.WriteLine(t.Exception.ToString());
}, TaskContinuationOptions.OnlyOnFaulted);

Console.ReadKey();
}

static async Task<IEnumerable<string>> TestAsync()
{
IEnumerable<string> list = null;

try
{
list = await TestTask();
}
catch (Exception)
{
Console.WriteLine("Caught!");
}


return list;
}

static Task<IEnumerable<string>> TestTask()
{
var task = new Task<IEnumerable<string>>(() =>
{
throw new AggregateException("This is a test");
});

task.Start();

return task;
}

最佳答案

只要在 VS 中断后点击继续,您就会看到它到达了您的 ContinueWith。这只是调试器的一个怪癖,因为它无法在您的代码中找到处理执行的 try/catch。

如果您不希望调试器停止并向您显示一条消息,您需要在调试器选项中禁用“Just My Code”,以便 Task 中的 try/catch被算作捕获异常的事物。

关于c# - 异步/等待抛出未处理的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41815236/

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