Try/Catch Wrap Around Task.Run not Handling Exception

安稳与你 提交于 2019-12-10 17:17:30

问题


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?


回答1:


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.




回答2:


As mentioned in Stephen's correct answer this happens only when the Debugger is on. Using this simple workaround you can re-throw the exception "outside" of Task.Run();

Exception exceptionOut = null;

await Task.Run(() =>
{
    try
    {
        // Your code
    }
    catch (Exception exceptionIn)
    {
        exceptionOut = exceptionIn;
    }
});

if (exceptionOut != null)
    throw exceptionOut;



回答3:


Your try/catch runs an async operation, thus does not hold the async operation, since the code is not guaranteed to be at that location when the exception is hit. Try including the try/catch within the Task.Run(() => {..});



来源:https://stackoverflow.com/questions/37282414/try-catch-wrap-around-task-run-not-handling-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!