How can I detect if Dispatcher.DisableProcessing is active?
An exception is raised if one tries to show a message box if the Dispatcher
is suspended (Dispatcher.DisableProcessing()
called).
InvalidOperationException: 'Dispatcher processing has been suspended' (see here).
Does anyone know how I can detect where the Dispatcher
is suspended or not (so I know when to call BeginInvoke()
)?
Edit 1:
In reaction to the Application.DispatcherUnhandledException event I'm trying to show a MessageBox. However, if this unhandled Exception was thrown during DataBinding (i.e. ItemsControl.ItemsSource
) the Dispatcher
is suspended. Trying to show a MessageBox
then fails. Always using Dispatcher.BeginInvoke()
solves the problem, but I don't want to do that unless really necessary.
Edit 2:
Using Reflection to accomplish this works like this:
开发者_StackOverflow社区var dispatcherType = typeof(Dispatcher);
var countField = dispatcherType.GetField("_disableProcessingCount", BindingFlags.Instance | BindingFlags.NonPublic);
var count = (int)countField.GetValue(Dispatcher.CurrentDispatcher);
var suspended = count > 0;
There is no public interface there so you don't have a legal way to say whether it's suspended or not. You still can use reflection, but generally speaking this indicates you are doing something totally wrong.
If you could give us more details we could suggest proper solution?
try this:
if(currentDispatcher.Thread.ThreadState == System.Threading.ThreadState.Suspended)
{
}
精彩评论