'WPF: Cannot perform this operation while dispatcher processing is suspended when checking if window is modal

I am getting the following exception when checking if a window is modal:

System.InvalidOperationException: Cannot perform this operation while dispatcher processing is suspended.
at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Threading.DispatcherOperation.Wait(TimeSpan timeout)
at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherOperation operation, CancellationToken cancellationToken, TimeSpan timeout)
at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)

I am checking if the window is modal in the following manner:

(bool)AssociatedObject.Dispatcher.Invoke(new Func<bool>(() => ComponentDispatcher.IsThreadModal));

I am using .Net Framework 4.0

What might be causing this error and how to fix it?



Solution 1:[1]

I was able to fix the problem by changing the way I check if a given window is modal. I changed the code to:

return (bool)typeof(Window).GetField("_showingAsDialog", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(AssociatedObject);

When examining the Window class one can notice that this field is being set to true when the window is being shown as dialog.

https://referencesource.microsoft.com/#PresentationFramework/src/Framework/System/Windows/Window.cs,61d39b218b53dbbe,references

Above link points to the code for .Net Framework 4.8. However, the same applies for .Net Framework 4.0.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yamamotooko