How to Handle “Cannot perform this operation while dispatcher processing is suspended.” Errors in WPF

I ran in to an error today in WPF like this:

InvalidOperationException: Cannot perform this operation while dispatcher processing is suspended

After doing a little digging I found that this was happening because I was calling  Dispatcher.PushFrame inside an event handler for TabItem.IsVisibleChanged. Looking at the MSDN documentation for Dispatcher.PushFrame I found that this exception will be raised if the dispatcher processing is disabled – and one of the times that WPF disables dispatcher processing is during the layout phase (has to do with preventing nested message loops, or something). It just so happened that this event was being raised while WPF was doing layout!

The solution? Use the Dispatcher to delay my event handler until the Dispatcher is  available to handle PushFrame calls. So this:

tabItem.IsVisibleChanged += new DependencyPropertyChangedEventHandler( Tab_IsVisibleChanged );

Becomes this:

tabItem.IsVisibleChanged += (o, e) => Dispatcher.BeginInvoke( new DependencyPropertyChangedEventHandler( Tab_IsVisibleChanged ), o, e);
Advertisement

Tags: , ,

2 Responses to “How to Handle “Cannot perform this operation while dispatcher processing is suspended.” Errors in WPF”

  1. Carl Scarlett Says:

    Awesome. This helped me out of a mess today, so thank you!

  2. Keith Fletcher Says:

    Nice! Just the info I was looking for. Thank you for sharing

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.