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.
source share