You, probably, want something like this:
// Trying to complete task again and again...
// you may want to give some number of attempt to complete, say
// for (int attempt = 1; attempt <= 3; ++i) {
while (true) {
// Let task 300 ms to completet before it'll be canceled
using (CancellationTokenSource cts = new CancellationTokenSource(300)) {
try {
await DoSomething(cts.Token);
// Task Succeeded, break the loop
break;
}
catch (TaskCanceledException) {
// Task Cancelled, keep on looping
;
}
}
}
Note, that you should have some support in DoSomething
:
async Task DoSomething(CancellationToken token)
instead of
async Task DoSomething()
since we should know how to cancel it. If you don't have
async Task DoSomething(CancellationToken token)
or alike signature, (with CancellationToken
), the bitter truth is that you can't cancel. You can try wait (and forget the task if it's not completed):
// Since we are going to forget running tasks, let's
// restrict number of attempts
for (int attempt = 1; attempt <= 3; ++attempt) {
Task task = DoSomething();
if (await Task.WhenAny(task, Task.Delay(300)) == task) {
// task has been completed before timeout
break;
}
// we forget task (alas, we can't cancel it) and try again
}