Try / Catch a Wrap around Task. Do not handle exception

I learned to use TPL and have a problem with the example I compiled from this article . I copy and paste the code in the same way as in the Task.Run example, but I get an error message: the exception is not 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);
    }
}

The error is shown here:

enter image description here

Is this sample code obsolete or am I missing something?

+4
source share
3 answers

This is just a misleading debugger message.

What actually happens is that the exception is thrown and then broken by the .NET platform (and not the user code), and then placed into the task.

, ( .NET - ), .

, . , , " ", , await . , , , await ed.

+5

, . , "" Task.Run();

Exception exceptionOut = null;

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

if (exceptionOut != null)
    throw exceptionOut;
0

Your try / catch starts the async operation, so it does not perform the async operation, because the code is not guaranteed to be in that place when the exception is removed. Try enabling try / catch inTask.Run(() => {..});

-1
source

All Articles