I just wonder whether a race condition occurs in the code below:
int readingFiles;
async Task<string> ReadFile (string file)
{
++readingFiles;
var text = await Stream.ReadFileAsync(file);
--readingFiles;
return text;
}
If ReadFile method is executed by a thread pool thread, readingFiles will be accessed by two different threads and the readingFiles variable is not protected by any synchronization idioms.
It means that the first update to readingFiles should not be visible to the other thread executing "--readingFiles". However, I've NEVER seen that readingFiles equals -1 after "--readingFiles". I check whether the same thread executes the ++ and -- operations by using Thread.CurrentThread. In most cases, it is not the same thread and I still do not see readingFiles as -1.
Even though there is a race condition and readingFiles is not volatile, why do not I see the effect of this race condition?
There is no race condition here. The .NET runtime will insert the appropriate memory barriers.
Also see the comments on: http://blogs.msdn.com/b/pfxteam/archive/2012/04/12/async-await-faq.aspx
Yes, TPL includes the appropriate barriers when tasks are queued and at the beginning/end of task execution so that values are appropriately made visible.
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