Cancelling a pending task synchronously on the UI thread

So we don’t want to be doing a synchronous wait as that would be blocking the UI thread, and also possibly deadlocking.

The problem with handling it asynchronously is simply that the form will be closed before you’re “ready”. That can be fixed; simply cancel the form closing if the asynchronous task isn’t done yet, and then close it again “for real” when the task does finish.

The method can look something like this (error handling omitted):

void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
    if (!_task.IsCompleted)
    {
        e.Cancel = true;
        _cts.Cancel();
        _task.ContinueWith(t => Close(), 
            TaskScheduler.FromCurrentSynchronizationContext());
    }
}

Note that, to make the error handling easier, you could at this point make the method async as well, instead of using explicit continuations.

Leave a Comment