I am using an external library that has async
methods, but not CancellationToken
overloads.
Now currently I am using an extension method fr
As you suggest you can cancel a task by passing in a CancellationToken
and then calling Cancel
.
As for how you'd go about triggering that cancellation depends on the nature of your application.
A few possible scenarios
In case 1 you simply cancel the task from your cancel button, for example
private void cancel_Click(object sender, RoutedEventArgs e)
{
...
cts = new CancellationTokenSource();
await MyAsyncTask(cts.Token);
cts.Cancel();
...
}
In case 2 you could start a timer when you start your task and then cancel the task after a set time using CancelAfter
, for example
private void start_Click(object sender, RoutedEventArgs e)
{
...
cts = new CancellationTokenSource();
cts.CancelAfter(30000);
await MyAsyncTask(cts.Token);
...
}
In case 3 you could do something with progress, for example
private void start_Click(object sender, RoutedEventArgs e)
{
...
Progress progressIndicator = new Progress(ReportProgress);
cts = new CancellationTokenSource();
await MyAsyncTask(progressIndicator, cts.Token);
...
}
void ReportProgress(int value)
{
// Cancel if no progress
}
Here are a few useful links Parallel programming, task cancellation, progress and cancellation, cancel tasks after set time, and cancel a list of tasks.