I have a task which runs a loop and delays for an interval each iteration. Once the CancellationTokenSource
calls Cancel()
I want my main code to Wait()
for the Task.Delay(interval)
to finish and the task to exit the loop before my code continues. I thought this code would work but it doesn't.
Instead my main code passes the t.Wait()
before the Loop exits. Why?
Main Method Code:
var cts = new CancellationTokenSource();
CancellationToken ct = cts.Token;
var t = Task.Run(() => { MyLoopTask(200, ct); });
// Prepare information
cts.Cancel();
t.Wait();
// Send Information
Task Code
private async Task MyLoopTask(int interval, CancellationToken cancelToken)
{
while (!cancelToken.IsCancellationRequested)
{
Debug.Print(" Still In Loop ");
// Do something
await Task.Delay(interval);
}
Debug.Print(" cancelled ");
//Clean up
}
You create a task with Task.Run
that fires and forgets the actual task you get back from MyLoopTask
.
Task.Run
is redundant here. You can just call MyLoopTask
and use the task it returns.
var t = MyLoopTask(200, ct);
// ...
t.Wait();
If you still have some reason to use Task.Run
you can do so by making sure the delegate waits for the actual task by awaiting it:
var t = Task.Run(async () => await MyLoopTask(200, ct));
// ...
t.Wait();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With