Exception exceptions in C # tasks without waiting

I have a GUI application in which I want to run something in a task, so it will not contain a user interface. I want the unhandled exception in the task to be passed to the application-level exception handler. But:

  • If I just throw an exception into the task, it will not reach the application level of the exception, unless I use wait / await
  • Async / Await - I call the method from the user interface constructor, so I can not use async / await there, since I need to continue with a constant. I just want to run a task and forget.

I was thinking about using dispatcher.invoke, what do you think?

public MainWindow()
{
        InitializeComponent();

        MyMethodAsync();

        InitializeA();
        IntiializeB();
}

private void MyMethodAsync()
{
     Task t = Task.Run(() =>
     {
          //Do some stuff
          throw new Exception("Throwing some unexpected exception");
     }).ContinueWith(MyContinueWith);
}

private void MyContinueWith(Task task)
{
    if (task.IsFaulted && task.Exception != null)
    {
         dispatcher.BeginInvoke(new Action(() =>
         {
            throw task.Exception;
         }), null);
    }
}
+4
source share
2

, . -, TaskScheduler.UnobservedTaskException , :

private void MyMethodAsync()
{
    // Note you should probably register only once, so this may not fit here.
    TaskScheduler.UnobservedTaskException += (s, e) => GlobalLogger.Log(e);
    Task t = Task.Run(() =>
    {
        // Do some staff
    }).ContinueWith(MyContinueWith);
}

, - , - try-catch:

private async Task MyMethodAsync()
{
    try
    {
       await Task.Run(() =>
       {
          // Do some staff
       });
       InvokeContinuation();
    }
    catch (Exception e)
    {
        // Log.
    }
}
+2

, , Task.Run, , , . , , . , I/O, .

, , ContinueWith , async. , , async/await . , , , , , .

0

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


All Articles