Addition after comments in the end
I have a windows form with a fairly long running method. So I thought I'd make it async.
Because sometimes the operator does not want to wait until it is finished, I give the opportunity to cancel the task:
private CancellationTokenSource = new CancellationTokenSource();
private async Task<TResult> DoLongProcessingAsync(CancellationToken token)
{
// do some long async processing; allow cancelling
await Task.Delay(TimeSpan.FromSeconds(30), token);
return new TResult() {...};
}
public async void ButtonStart_Clicked(object sender, ...)
{
this.buttonStart.Enabled = false;
this.ShowBusy(true);
await this.DoLongProcessing(this.cancellationTokenSource.Token);
this.ShowBusy(false);
this.buttonStart.Enabled = true;
}
Now suppose the operator closes the form before DoLongProcessingAsync is completed.
private async void OnFormClosing(object sender, ...)
{
bool closingAlloged = this.AskOperatorIfClosingAllowed();
if (closingAllowed)
{
this.cancellationTokenSource.Cancel();
// TODO: await until DoLongProcessingAsync is finished
}
}
How do I await until LongProcessing is finished?
Addition
Some said I should await the task. But alas, the Task is a local variable inside ButtonStart_Clicked. I'm not sure if I should make it a field inside the class.
Until now I wasn't planning it, but as long as it is a local variable, I can start several tasks, by clicking several times, and cancel them all by cancelling the CancellationTokenSource.
Or is this really a no-no?