// THIS METHOD RUNS ON A SECONDARY UI THREAD (THREAD WITH A DISPATCHER)
        private void MethodRunningOnSecondaryUIThread()
        {
            var secondaryUiThreadId = Thread.CurrentThread.ManagedThreadId;

            try
            {
                // On secondary thread, show a new Window before starting a new Dispatcher
                // ie turn secondary thread into a UI thread
                var window = new SecondaryUIThreadWindow();
                window.Show();
                Dispatcher.Run();
            }
            catch (Exception ex)
            {
                // Dispatch the exception back to the main ui thread and reraise it
                Application.Current.Dispatcher.Invoke(
                    DispatcherPriority.Send,
                    (DispatcherOperationCallback) delegate
                {
                    // THIS CODE RUNS BACK ON THE MAIN UI THREAD
                    string msg = $"Exception forwarded from secondary UI thread {secondaryUiThreadId}.";
                    throw new Exception(msg, ex);
                }
                    , null);

                // NOTE - Application execution will only continue from this point
                //        onwards if the exception was handled on the main UI thread
                //        by Application.DispatcherUnhandledException
            }
        }
Exemple #2
0
        // THIS METHOD RUNS ON A SECONDARY UI THREAD (THREAD WITH A DISPATCHER)
        private void MethodRunningOnSecondaryUIThread()
        {
            var secondaryUiThreadId = Thread.CurrentThread.ManagedThreadId;
            try
            {
                // On secondary thread, show a new Window before starting a new Dispatcher
                // ie turn secondary thread into a UI thread
                var window = new SecondaryUIThreadWindow();
                window.Show();
                Dispatcher.Run();
            }
            catch (Exception ex)
            {
                // Dispatch the exception back to the main ui thread and reraise it
                Application.Current.Dispatcher.Invoke(
                    DispatcherPriority.Send,
                    (DispatcherOperationCallback) delegate
                    {
                        // THIS CODE RUNS BACK ON THE MAIN UI THREAD
                        string msg = $"Exception forwarded from secondary UI thread {secondaryUiThreadId}.";
                        throw new Exception(msg, ex);
                    }
                    , null);

                // NOTE - Application execution will only continue from this point
                //        onwards if the exception was handled on the main UI thread
                //        by Application.DispatcherUnhandledException
            }
        }