How to forward an exception from Task to the main stream of a WinForms application?

Scenario: There is a button, this button creates a task that performs some code in the background, an unhandled exception occurs in the task, and the main program needs to know about it.

I read MSDN and offered the following there:

1) Set Task.Wait, but in this case my UI will freeze.

2) Check the status of the Task. But where is it better to check and with what periodicity?

I did not find any events for Task.

    1 answer 1

    You can subscribe to an "event" using the ContinueWith method:

     task.ContinueWith(t => Console.WriteLine(t.Exception), TaskContinuationOptions.OnlyOnFaulted) 

    I also advise you to explore the use of the keywords async and await - they simplify a lot.

    If you use libraries for logging, then see if the method you need is there. For example, if you use NLog and you need to output an asynchronous error to the log, you can use the Logger.SwallowAsync method

    • It should be clarified that this construction should be performed in the UI stream. Otherwise, you will need to explicitly pass the necessary task scheduler to ContinueWith() . For the console, of course, irrelevant, but the author asked about WinForms. - andreycha
    • Hello. And if I still use the console and logs, I simply write to the file, since it seems to me that NLog is very unjustified in attributing. try { Task.Run(() =>Method()); } catch (ThreadAbortException) { return; } catch (Exception error) { Log.Write(error); } try { Task.Run(() =>Method()); } catch (ThreadAbortException) { return; } catch (Exception error) { Log.Write(error); } - Leonid