The following code works as expected – both services start at the same time.
List<Service> services = [ new Service(), new Service() ];
foreach (Service service in services)
{
Task task = service.StartAsync();
}
Console.ReadLine();
class Service
{
public async Task StartAsync()
{
await Console.Out.WriteLineAsync($"{DateTime.Now.ToString("HH:mm:ss")}tStarted");
await Task.Delay(TimeSpan.FromSeconds(1));
//Simulate some synchronous work.
Thread.Sleep(10_000);
await Console.Out.WriteLineAsync($"{DateTime.Now.ToString("HH:mm:ss")}tFinished");
}
}
Output is:
20:32:25 Started
20:32:25 Started
20:32:35 Finished
20:32:35 Finished
But when you change the delay from TimeSpan.FromSeconds(1)
to TimeSpan.FromMicroseconds(1)
, the output is:
20:40:10 Started
20:40:20 Finished
20:40:20 Started
20:40:30 Finished
Why does changing the delay affect behavior? Is there a race condition going on?