Search code examples
c#wpfmultithreadingexceptiondispatcher

External thread exception doesn't catched in the DispatcherUnhandledException event


I'm trying to handle any background thread exception using the App.DispatcherUnhandledException event because I'm comprehensively catch them and writing them to the log there. I have tried to do it that way below but the event doesn't got raised and my app got crashed.

public class MainWindow : Window
{
    public MainWindow()
    {
        client = new Client();
        client.OnSocketError += (s, e) => Dispatcher.Invoke(() => throw e.Exception); // re-throwing
        client.Connect("192.168.1.5", "1234");
    }
}

It is possible to re-throw the exception to the main thread?

Note that event got raised when the exception thrown from the main thread.


Solution

  • I replaced this line:

    Dispatcher.Invoke(() => throw e.Exception);
    

    With this one:

    Dispatcher.BeginInvoke(new Action(() => throw e.Exception));
    

    And now it works properly.

    I guess the reason is that Invoke method left the EventHandler blocked and now the BeginInvoke method doesn't.