Why does this task not end before my code passes a wait command

I have a task that starts a loop and delays the interval at each iteration. As soon as the CancellationTokenSource calls Cancel() , I want my main Wait() code for Task.Delay(interval) complete, and the task to complete the loop to my code. I thought this code would work, but it is not.

Instead, my main code passes t.Wait() until Loop exits. Why?

The 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 } 
+6
source share
1 answer

You create a task with Task.Run , which starts and forgets the actual task that you are returning from MyLoopTask .

Task.Run is redundant here. You can simply call MyLoopTask and use the task that it returns.

 var t = MyLoopTask(200, ct); // ... t.Wait(); 

If you still have reason to use Task.Run , you can do this by making sure that the delegate is waiting for the real task, waiting for it:

 var t = Task.Run(async () => await MyLoopTask(200, ct)); // ... t.Wait(); 
+9
source

All Articles