I have code with looks something like:
I was trying to avoid putting it in a Task.Run because it is async and should run fine on the main thread
However it does not do a context switch (and will run forever), unless I insert a Task.Delay into the loop
Is there a better way of achieving this (Without Task.Run)?
var tasks = new List<Task>();
var cts = new CancellationTokenSource();
tasks.Add(DoSomething(cts.Token));
cts.Cancel();
Task.WaitAll(tasks.ToArray());
Console.WriteLine("Done");
async Task DoSomething(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
await Task.CompletedTask;
await Task.Delay(1); // Without this is doesn't do context switch
}
}
I'm trying to unit test cancellation when I have a heavy workload an encountered this problem.