Race Status in Async / Await Code

I'm just wondering if the race condition arises in the code below:

int readingFiles; async Task<string> ReadFile (string file) { ++readingFiles; var text = await Stream.ReadFileAsync(file); --readingFiles; return text; } 

If the ReadFile method is executed by a thread pool thread, readFiles will be available in two different threads, and the readFiles variable will not be protected by any synchronization idioms.

This means that the first readFiles update should not be visible to another thread executing "-readingFiles". However, I NEVER saw that readFiles is -1 after "--readingFiles". I check if the same thread performs ++ and - operations with Thread.CurrentThread. In most cases, this is not the same thread, and I still don't see readFiles as -1.

Despite the fact that there is a race condition, and reading Files is not mutable, why do not I see the effect of this race condition?

+7
multithreading c # asynchronous race-condition async-await
source share
2 answers

There is no race. .NET runtime will insert appropriate memory barriers.

Also see comments on: http://blogs.msdn.com/b/pfxteam/archive/2012/04/12/async-await-faq.aspx

Yes, TPL includes appropriate barriers when tasks are queued, and at the beginning / end of task execution, so that the values ​​are accordingly visible.

+9
source share

Here you can find a few things.

First, which executable file are you using? When Await fires, it uses the current synchronization context, so your expected code can be serialized into 1 thread of the user interface.

Also, since there is no memory barrier / volatility protection for the variable, your threads can read individually cached values ​​(as @ Spo1ler mentions in his post)

In addition, the thread pool can choose to run both of your requests in the same thread (within its rights for this - you allow .net / windows to decide when and how to distribute threads)

However, you really must protect access to the variable through synchronization or blocking operations.

0
source share

All Articles