I am trying to understand the inner workings of the Asp.net Identity system and have seen that all of the async
calls it seems to make use of the WithCurrentCulture()
task extension. I have looked at the source code for that extension and I cannot figure out what it is doing or why.
From documentation
Configures an awaiter used to await this Task to avoid marshalling the continuation back to the original context, but preserve the current culture and UI culture.
Can someone please shed some light on it?
It executes the task continuation with Thread.CurrentCulture
and Thread.CurrentUICulture
set to the same values as they are on the thread where it was called from.
By default, the culture of new threads is set to the Windows system culture. For example, say you are awaiting a task, and you have explicitly set Thread.CurrentCulture
to a different culture. Now when you await a task with ConfigureAwait(false)
, the code after the await
might execute on a different thread than the code before the await
. Since it is a different thread, it may have CurrentCulture
set back to the system culture.
Thread.CurrentThread.CurrentCulture = someCulture;
await SomeTask().ConfigureAwait(false);
bool equal = Thread.CurrentThread.CurrentCulture == someCulture; // Might be false!
If you want to have the culture stay the same after the await
, use WithCurrentCulture()
. It does the same thing as ConfigureAwait(false)
, but also keeps the culture from the original thread.
Thread.CurrentThread.CurrentCulture = someCulture;
await SomeTask().WithCurrentCulture();
bool equal = Thread.CurrentThread.CurrentCulture == someCulture; // Will be true
Note that if you OMIT ConfigureAwait(false)
and WithCurrentCulture()
, the code after the await
will run on the same thread as before, so you don't have to worry about any of this. WithCurrentCulture()
only applies in the case where you want to optimize your code by avoiding an extra context switch.
Side note: you can also control the default culture for new threads by setting CultureInfo.DefaultThreadCurrentCulture
and CultureInfo.DefaultThreadCurrentUICulture
.
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