Close window from another thread in WPF using Dispatcher.Invoke

I have a problem that I cannot solve even after looking at various information about Dispatcher.Invoke.

There is a MainWindow that creates a task, launches this task, and opens a progress window. When the task completes, I need to close the execution window. Here is what I have:

private void Button_Click(object sender, RoutedEventArgs e) { Task task = new Task(_vm.WriteToDB); task.ContinueWith(ExceptionHandler, TaskContinuationOptions.OnlyOnFaulted); task.ContinueWith(RanToCompletion, TaskContinuationOptions.OnlyOnRanToCompletion); task.Start(); _frmProgress = new Progress(task); _frmProgress.DataContext = _vm; _vm.ProgressText = "Connecting to update server..."; _frmProgress.ShowDialog(); } public void RanToCompletion(Task task) { Progress.FormCloseDelegate FormCloseDelegate = new Progress.FormCloseDelegate(_frmProgress.Close); if (_frmProgress.Dispatcher.CheckAccess()) _frmProgress.Close(); else _frmProgress.Dispatcher.Invoke(DispatcherPriority.Normal, FormCloseDelegate); } 

FormCloseDelegate is defined in the Progress window:

 public delegate void FormCloseDelegate(); 

In the current implementation above, the code compiles and runs, but the execution form does not close after the task is completed. Any ideas?

I would also be open to other ideas to solve this problem. Perhaps I generally went the wrong way.

Thanks.

+4
source share
1 answer

As I mentioned in the comments, I blocked the closing of the Progress window when the user clicked the close button with e.Cancel = true in the Window_Closing event. It also blocked the call in code to close the window.

I updated the RanToCompletion method after I realized that I didn't need a user delegate at all:

 public void RanToCompletion(Task task) { if (_frmProgress.Dispatcher.CheckAccess()) _frmProgress.Close(); else _frmProgress.Dispatcher.Invoke(DispatcherPriority.Normal, new ThreadStart(_frmProgress.Close)); } 
+7
source

All Articles