简体   繁体   English

处理Task.Run内部的异常

[英]Handling Exceptions Inside Task.Run

I'm trying to deal with exceptions inside of tasks, so far I've looked at the following links: 我正在尝试处理任务内部的异常,到目前为止,我已经查看了以下链接:

https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/exception-handling-task-parallel-library https://docs.microsoft.com/zh-cn/dotnet/standard/parallel-programming/exception-handling-task-parallel-library

How to handle Task.Run Exception 如何处理Task.Run异常

If I am correct, they suggest that the following code would not cause a User-Unhandled Exception. 如果我是正确的,他们建议以下代码不会导致用户未处理的异常。

    public async void TestMethod()
    {
        try
        {
            await Task.Run(() => { throw new Exception("Test Exception"); });
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }

However, I am getting a User-Unhandled Exception. 但是,我收到了一个用户未处理的异常。 I want to handle the exception outside of the Task so I can avoid writing code for changing the UI from a different thread. 我想在Task之外处理异常,因此可以避免编写用于从其他线程更改UI的代码。 What am I doing wrong? 我究竟做错了什么?

Here is a printscreen of the exception: 这是例外情况的打印屏幕:

在此处输入图片说明

To answer your original question, before you edited it, one of the features of await is that it will "unwrap" not only the return value, but any exceptions too. 为了回答您的原始问题,在您对其进行编辑之前, await的功能之一是它不仅可以“包装”返回值,而且还可以“包装”任何异常。 So if you need to catch an exception, it will not be an AggregateException like it would be if you used .Wait() or .Result . 因此,如果您需要捕获一个异常,它将不会像使用.Wait().Result那样,成为AggregateException

That's a Good Thing™ 那是一件好事™

Also, it looks like Visual Studio is configured to break on all exceptions, even handled ones. 此外,看起来Visual Studio已配置为打破所有异常,甚至处理异常。 This is handy (I always keep VS set like that because sometimes weird things can happen when exceptions are caught and hidden), but you just have to be aware of it. 这很方便(我总是保持VS那样的设置,因为有时在捕获和隐藏异常时会发生奇怪的事情),但是您只需要意识到这一点即可。 You can press F5 or F10 to continue execution and it should continue into the catch block. 您可以按F5或F10继续执行,它应继续进入catch块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM