Friday, June 8, 2012

System.InvalidOperationException: Dispatcher processing has been suspended, but messages are still being processed.

In a WPF application, when I try to open a specific page, the application crashes with the following error message:
“System.InvalidOperationException: Dispatcher processing has been suspended, but messages are still being processed. at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)”
When I looked at the code, I was calling a method on my ViewModel when a specific event was triggered on my view. Inside this method I try to open a MessageBox and show a warning.
The view code:
private void SampleView_Load(object sender, EventArgs args)
{
            this
               .OnEventTrigger(grdProducts, "SizeChanged")
               .ExecuteCommand("Open1");

}

The viewmodel code:
 
public void Open1()
{
 _windowManager.OpenMessageBox("Open 1 method called.", false);
}

The ExecuteCommand() is a piece of functionality I created myself to have a fluent API to link events to commands(method call on the view model).

When I searched for more information about this exception, I found the following:

The exception is done on purpose to prevent reentrancy bugs caused by weirdness resulting from altering the visual tree, while such an event (which itself has been triggered by the visual tree altering) is firing. If you really must confirm something when the state of a UI element changes, delaying with Dispatcher.BeginInvoke is probably the right thing to do.

This code is already triggered before the form is fully loaded, and this explains why the exception happens. To solve it I changed my ExecuteCommand implementation to invoke the method on the ViewModel on the UI thread:
  

private void ExecuteCommand(Command command)
{
 if (command == null)
     return;

 Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => command.Execute(null)));
}