Your source code does what you never need to do: calling async void methods. And the problem for handling exceptions is one of the reasons for this.
Look at the event handlers one by one:
Application.ThreadException handles only exceptions in the Winforms UI thread. The exception never got into the user interface thread, so this event does not fire.TaskScheduler.UnobservedTaskException handles exceptions from Task that are unobservable (and even then it does it when they are completed, which can take a long time if you do not allocate a lot of memory). But an inconspicuous exception is not tied to any Task , therefore it also does not work.AppDomain.CurrentDomain.UnhandledException handles all exceptions that are still considered unobservable after the previous two event handlers. But it cannot be used to set an exception, as it is, so the application still terminates. This is the only handler that really fires.
Why exactly the first two handlers do not work? In your code, you have Task.Run(() => new IGetRun().Run1()) , where Run1() is the async void method that throws an exception.
If there is an invisible exception in the async void method, the exception returns to the current synchronization context. But since this method works in a thread pool thread (due to Task.Run() ), there is no synchronization context. Thus, an exception is thrown into the thread pool thread, which is not observed for the first two event handlers.
As you already found out, the fix for this problem is to use the async Task and await methods correctly.
Updated Run1() code now uses the async Task method. This Task deployed by Task.Run() and then await ed, so the exception is thrown to Hello() Task . This, in turn, is await ed from the async void button1_Click in the user interface thread.
All of this means that there are no invisible Task exceptions and that the exception is returned in the context of user interface synchronization. In Winforms, this means that Application.ThreadException raised, which is exactly what you are observing.
svick source share