Try/Catch Wrap Around Task.Run not Handling Exception

后端 未结 3 1784
故里飘歌
故里飘歌 2021-01-18 13:11

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

3条回答
  •  孤独总比滥情好
    2021-01-18 13:34

    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;
    

提交回复
热议问题