I have a problem that I cannot solve even after looking at the various information about Dispatcher.Invoke.
There is a MainWindow that creates a task, starts that task and then opens a progress window. When the task completes, I need to close the progress window. Here’s 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();
With the current implementation above, the code compiles and runs but the Progress form is not closed once the task completes. Any ideas?
I’d also be open to other ideas to solve this. Maybe I’ve gone down the wrong path altogether.
Thank you.
Well as I mentioned in comments, I was blocking closing of the Progress window when the user clicked on the close button with e.Cancel=true in the Window_Closing event. This was blocking the call in the code to close the window also.
I updated the RanToCompletion method after realising that I didn’t need a custom delegate at all: