Question

I use the following Code

var UiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
CancellationToken cancellationToken = cancellationTokenSource.Token;
const TaskContinuationOptions continuationOptions = TaskContinuationOptions.OnlyOnRanToCompletion;

Task<string> task = Task<string>.Factory.StartNew(() => getSomeText(), cancellationToken);
task.ContinueWith(t => label.Text = t, cancellationToken, continuationOptions, UiScheduler);

To update the UI after some Background Task. But if the Form is closed before the task is finished, the update is done anyway. Is there some best practice how to avoid this? Some controls begin to Bug in response to using them when the form is already gone. I for now check "Disposing" and "IsDisposed" to avoid this but I'm not sure if this is the right way and whether there may be other threading problems / race conditions with that. Thx for any help!

Was it helpful?

Solution

Checking for Form.IsDisposed on the UI thread before updating the UI is the way to go, and will avoid any race conditions.

If you handle the FormClosing event as suggested by John Willemse, you will be able to request cancellation of the task - but there can still be a race condition which means the task will complete and update the UI.

OTHER TIPS

You can handle the FormClosing event to intercept the closing of a form. The FormClosingEventArgs contains information about why the form is closed, e.g. user request, system shutdown, etc. You can then respond by cancelling the task or the closing of the form.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top