尝试/捕获绕回Task.Run不处理异常 [英] Try/Catch Wrap Around Task.Run not Handling Exception

查看:251
本文介绍了尝试/捕获绕回Task.Run不处理异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在学习使用TPL,并且对从此



此代码示例过时了还是丢失了某些东西?

解决方案

这只是一个误导性的调试器消息。



实际发生的是则引发异常,然后由.NET框架(不是用户代码)捕获该异常,然后将其放置在任务上。



因此,而技术上错误消息是正确的(被.NET框架捕获-用户代码未处理),在这种情况下不是很有帮助。



不幸的是,还有调试器没有很多替代方案。在异常离开用户代码的那一刻,调试器无法展望未来,以知道该异常将被放置在特定任务上,并且您的代码将等待该任务。它必须立即做出是否通知您的决定,而不知道是否将等待 ed该任务。


I've been learning to use TPL and have an issue with an example I gathered from this article. I copy and pasted the code exactly as in the Task.Run example but get an error message saying the exception isn't handled:

private async void button1_Click(object sender, EventArgs e)
{
    try
    {
        await Task.Run(() =>
        {
            Thread.Sleep(1000);
            throw new InvalidOperationException("Hi!");
        });
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

Here's a picture of the error:

Is this code example outdated or am I missing something?

解决方案

This is just a misleading debugger message.

What's actually happening is that the exception is being thrown, then caught by the .NET framework (not user code), and then placed on the task.

So, while technically the error message is correct (it's caught by the .NET framework - unhandled by user code), it's not very helpful in this case.

Unfortunately, there's also not a lot of alternatives for the debugger. At the point when the exception leaves user code, the debugger has no way of "looking into the future" to know that the exception will be placed on a specific task and that your code will await that task. It has to make a decision immediately whether to notify you or not, without knowing whether the task will be awaited.

这篇关于尝试/捕获绕回Task.Run不处理异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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