Yet another question about thread safety and async/await. I don't understand why my second increment is not thread safe.
class Program
{
static int totalCountB = 0;
static int totalCountA = 0;
static async Task AnotherTask()
{
totalCountA++; // Thread safe
await Task.Delay(1);
totalCountB++; // not thread safe
}
static async Task SpawnManyTasks(int taskCount)
{
await Task.WhenAll(Enumerable.Range(0, taskCount)
.Select(_ => AnotherTask()));
}
static async Task Main()
{
await SpawnManyTasks(10_000);
Console.WriteLine($"{nameof(totalCountA)} : " + totalCountA); // Output 10000
Console.WriteLine($"{nameof(totalCountB)} : " + totalCountB); // Output 9856
}
}
What I understand :
totalCountA++
is thread safe because, until that point, the code is completely sync.- I understand that
await
may be run on the threadpool, but I didn't expect that the code resuming theawait
will be completely multi-threaded.
According to the some answers/blogs, async/await should not create a new thread :
- Does the use of async/await create a new thread?
- https://blog.stephencleary.com/2013/11/there-is-no-thread.html
I'm really missing something big here.