Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the culture kept after ConfigureAwait(false)

I have the following async code:

// Main system culture is English here
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("es");

WriteLine($"{Thread.CurrentThread.ManagedThreadId}:Culture:{Thread.CurrentThread.CurrentCulture}");

await Task.Delay(1).ConfigureAwait(false);

WriteLine($"{Thread.CurrentThread.ManagedThreadId}:Culture:{Thread.CurrentThread.CurrentCulture}");

The resul I expected would be to have a different thread id after the await and that new thread id having the unmodified system culture again.

This is not happening; the thread is indeed different from the previous, but the culture is somehow flowing from the previous thread.

Why is it keeping the culture if I suggested with ConfigureAwait that I don't need to keep the SynchronisationContext? It is my understanding that the culture is not stored on the ExecutionContext therefore I am not sure why this is happening.

This is a Console application.

Full example code: https://pastebin.com/raw/rE6vZ9Jm

like image 363
user4388177 Avatar asked Aug 06 '17 10:08

user4388177


2 Answers

This is expected behaviour as of .NET 4.6.

The reason Julien could not reproduce it is that he's likely targeting a lower version of the framework (in 4.5.2, for instance, culture doesn't flow).

Here is the official documentation on the subject.

Specifically note the following:

... starting with apps that target the .NET Framework 4.6, asynchronous operations by default inherit the values of the CurrentCulture and CurrentUICulture properties of the thread from which they are launched. If the current culture or current UI culture differs from the system culture, the current culture crosses thread boundaries and becomes the current culture of the thread pool thread that is executing an asynchronous operation.

like image 158
Kirill Shlenskiy Avatar answered Sep 28 '22 02:09

Kirill Shlenskiy


A quick test on a new VS2017 Console project shows this output (en-GB is my default culture):

1:Culture:es
4:Culture:en-GB

Which is what you (and I) expected. Maybe something else is setting the culture independently?

like image 26
Julien Adam Avatar answered Sep 28 '22 01:09

Julien Adam