views:

30

answers:

1

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?

+1  A: 

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.

Stephen Cleary
The way I'm dealing with caught exceptions is irrelevant. I could put some logging or whatever there. The problem is that the exception handling code is never executed.
jpbochi
That's because the exception is thrown on another thread - the `Dispatcher` thread.
Stephen Cleary
@Sthepen: I know that. I was expecting to get a TargetInvocationException or something like it.
jpbochi
Exceptions are not propogated across threads automatically. I posted a sample that uses .NET 4.0 `Task`s to propogate the exception.
Stephen Cleary
This looks like a reasonable workaround, but you got rid from the Dispatcher altogether. Do you think there's a way to do it with using a Dispatcher? Also, do you have any idea why Windows Forms controls propagate exceptions and WPF Dispatchers don't?
jpbochi
`FromCurrentSynchronizationContext` does use the `Dispatcher` underneath (when running on WPF). Is there a particular reason you'd need `Dispatcher` explicitly? I believe `Control.Invoke` propogated exceptions just because that "felt right" to the WinForms team; WPF re-evaluated everything and determined that it was a fair amount of overhead for something that was rarely used (that's just my guess).
Stephen Cleary
I'm building an small component that would receive the Dispatcher and use it to invoke event-like delegates. In order to implement your idea, I'd have to change the interface of my component. I'd like to avoid it if I can.
jpbochi
In that case, I'd actually recommend moving to a `Task`-based interface or something else based on `SynchronizationContext` such as the [event-based asynchronous pattern](http://msdn.microsoft.com/en-us/library/wewwczdw.aspx). The reason is that `SynchronizationContext`-based approaches will work with WPF or Windows Forms transparently, and (with a bit more work) ASP.NET, console apps, windows services, etc. So if your goal is a reusable component, stick with `SynchronizationContext`.
Stephen Cleary
However, if you decide to stay with `Dispatcher`, then you'll actually have to catch the exception and marshal it back yourself (e.g., by replacing the delegate's return value with an object that can represent either a successful return value or an exception). One final hint: if you can use the [Rx library](http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx), then check out `System.Diagnostics.ExceptionExtensions.PrepareForRethrow`, which preserves the call stack of an exception when throwing it on the other thread (otherwise, the call stack is lost).
Stephen Cleary
(cont.) Windows Forms uses an undocumented method to preserve the exception call stack, I believe.
Stephen Cleary
I'm convinced. Can you put the comment that I voted on your answer? I'll accept it then. :)
jpbochi
@jpbochi: OK; I merged that comment into my answer and wrote a bit more (clarification).
Stephen Cleary
Thanks! Answer accepted
jpbochi