C # task exception management

I am launching a solution containing 2 projects: application and sdk.

Through the application, I create an sdk instance so that the application can start. The problem is that when I get an exception in the part of the code running inside the task, the Unhandled Exception is not thrown out, so my application continues to work and does not understand that the unexpected is happening in the SDK.

I am registered for an event AppDomain.CurrentDomain.UnhandledExceptionin the application and SDK, but as said, when an exception is thrown in the Task, the event handler is not called.

Is there something I am missing?

+4
source share
3 answers

( ) .

- , await. :

try
{
    await task;
}
catch (Exception e)
{
    // handle exception
}

( ), task.Wait(), AggregateException, , InnerExceptions , (.. task.ContinueWith(t => // handle exception))

UnobservedTaskException

.Net 4.0 Task . TaskScheduler.UnobservedTaskException ( UnhandledException). .Net 4.5 , , .

( , ), <ThrowUnobservedTaskExceptions enabled="true"/>, . , :

  • .Net , , - , ( , ). , .
  • , , .

await . UnobservedTaskException , .

+5

a Task , , IsFaulted Exception Task.

, , MSDN

UnobservedTaskException TaskScheduler. , , , UnhandledException AppDomain. MSDN

+3

, , , , SDK .

( @l3arnon ): Task .NET 4.0, .NET 4.5 UnobservedTaskException. , .NET 4.5 , .NET 4.0, , .

You can return to the behavior of .NET 4.0 with the help of app.config andThrowUnobservedTaskExceptions`                                   

There are several other solutions to this problem:

  • use await Task.Runin your code. awaitwill open an exception from inside the task.
  • If you do not want to wait and want to use the Fire and Forget approach, you can attach a sequel:

    Task.Run(() => {}).ContinueWith(task => { */ Handle Exceptions here */ },
                                    TaskContinutationOptions.OnlyOnFaulted);
    
+3
source

Source: https://habr.com/ru/post/1570863/


All Articles