diff --git a/source/Components/Xceed.Wpf.AvalonDock/Controls/FocusElementManager.cs b/source/Components/Xceed.Wpf.AvalonDock/Controls/FocusElementManager.cs index 4dac1b19..df8ca871 100644 --- a/source/Components/Xceed.Wpf.AvalonDock/Controls/FocusElementManager.cs +++ b/source/Components/Xceed.Wpf.AvalonDock/Controls/FocusElementManager.cs @@ -17,6 +17,7 @@ This program is provided to you under the terms of the Microsoft Public using System; using System.Collections.Generic; using System.Linq; +using System.Reflection; using System.Windows.Input; using System.Windows.Interop; using System.Windows; @@ -53,10 +54,18 @@ internal static void SetupFocusManagement( DockingManager manager ) _windowHandler.FocusChanged += new EventHandler( WindowFocusChanging ); //_windowHandler.Activate += new EventHandler(WindowActivating); _windowHandler.Attach(); - - if (Application.Current != null) - //Application.Current.Exit += new ExitEventHandler( Current_Exit ); - Application.Current.Dispatcher.Invoke(new Action(() => Application.Current.Exit += new ExitEventHandler(Current_Exit))); + if (Application.Current != null) + { + //Application.Current.Exit += new ExitEventHandler( Current_Exit ); + //Application.Current.Dispatcher.Invoke(new Action(() => Application.Current.Exit += new ExitEventHandler(Current_Exit))); + + // For resolve issue "System.InvalidOperationException: Cannot perform this operation while dispatcher processing is suspended." make async subscribing instead of sync subscribing. + Action subscribeToExitAction = new Action(() => Application.Current.Exit += new ExitEventHandler(Current_Exit)); + int disableProcessingCount = (int?)typeof(Dispatcher).GetField("_disableProcessingCount", BindingFlags.Instance | BindingFlags.NonPublic)?.GetValue(Dispatcher.CurrentDispatcher) ?? 0; + var dispatcherResult = disableProcessingCount == 0 + ? Application.Current.Dispatcher.Invoke(subscribeToExitAction) + : Application.Current.Dispatcher.BeginInvoke(subscribeToExitAction); + } } manager.PreviewGotKeyboardFocus += new KeyboardFocusChangedEventHandler( manager_PreviewGotKeyboardFocus );