Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why exceptions are not propagated by WPF Dispatcher.Invoke?

Here's my hypothetical example. I have a very simple WPF window with a one Button. The Button.Click event has a handler that goes like this.

Action doit = () =>
{
    Action error = () => { throw new InvalidOperationException("test"); };

    try {
        this.Dispatcher.Invoke(error, DispatcherPriority.Normal);
    } catch (Exception ex) {
        System.Diagnostics.Trace.WriteLine(ex);
        throw;
    }
};
doit.BeginInvoke(null, null);

I would expect that the exception would be caught and written down by the Trace.WriteLine call. Instead, no exception is caught and the application breaks.

Does anybody knows of an possible explanation for this to happen? And what workaround do you suggest in order to catch exceptions thrown by the delegate invoked by Dispatcher.Invoke?

Update 1: I put a throw in the exception handling code. I don't want to actually ignore the exception. The whole point of my question is to handle it correctly. The problem is that the exception handling code is never executed.

Remember that this is an hypothetical example. My real code does not look like that. Also, assume that I can't change the code in the method to be invoked.

Update 2: Consider this similar example. Instead of a WPF window, I have a Windows Forms window. It has a button with the almost exactly the same handler. The only difference is in the invocation code. It goes like this.

this.Invoke(error);

In Windows Forms, the exception handling code is executed. Why the difference?

like image 689
jpbochi Avatar asked Jun 24 '10 20:06

jpbochi


People also ask

What does dispatcher invoke do?

Invoke(Action, DispatcherPriority, CancellationToken) Executes the specified Action synchronously at the specified priority on the thread the Dispatcher is associated with.

What is Dispatcher BeginInvoke?

BeginInvoke(DispatcherPriority, Delegate, Object) Executes the specified delegate asynchronously at the specified priority and with the specified argument on the thread the Dispatcher is associated with.

What is the use of a dispatcher object in WPF?

A dispatcher is often used to invoke calls on another thread. An example would be if you have a background thread working, and you need to update the UI thread, you would need a dispatcher to do it.

Is dispatcher invoke thread safe?

the Dispatcher can't just drop code into your thread, it can only execute code when the application is in the "message loop". Any code you write doesn't have message loops unless you explicitly wrote them.


1 Answers

UPDATED: To observe the exception in the other thread, you want to use a Task, queue it to the Dispatcher thread (using TaskScheduler.FromCurrentSynchronizationContext), and wait on it, as such:

var ui = TaskScheduler.FromCurrentSynchronizationContext();
Action doit = () => 
{ 
    var error = Task.Factory.StartNew(
        () => { throw new InvalidOperationException("test"); },
        CancellationToken.None,
        TaskCreationOptions.None,
        ui); 

    try { 
        error.Wait(); 
    } catch (Exception ex) { 
        System.Diagnostics.Trace.WriteLine(ex); 
    } 
}; 
doit.BeginInvoke(null, null); 

UPDATED (again): Since your goal is a reusable component, I do recommend moving to a Task-based interface or something else based on SynchronizationContext such as the event-based asynchronous pattern, instead of basing the component on Dispatcher or ISynchronizeInvoke.

Dispatcher-based components only work on WPF/Silverlight; ISynchronizeInvoke-based components only work on Windows Forms. SynchronizationContext-based components will work with WPF or Windows Forms transparently, and (with a bit more work) ASP.NET, console apps, windows services, etc.

The event-based asynchronous pattern is the old recommended way of writing SynchronizationContext-based components; it's still around for .NET 3.5-era code. If you're on .NET 4, though, the task parallel library is much more flexible, clean, and powerful. The TaskScheduler.FromCurrentSynchronizationContext uses SynchronizationContext underneath, and is the New Way to write reusable components that need this kind of synchronization.

like image 79
Stephen Cleary Avatar answered Sep 22 '22 23:09

Stephen Cleary