C# notes: Preservation of the thread’s current culture when working with async methods

Posted: (EET/GMT+2)

 

The support for asynchronous tasks and the async/await keywords in C# can make concurrent programming much easier than it was before with plain threads. However, there are couple of things that you might need to worry about, especially if you are working with older .NET framework versions.

Assume you'd had code similar to this:

private async void SomeMethod() {
  // set the default culture for the thread
  Thread.CurrentThread.CurrentCulture = ...some culture...;
  
  // launch a long-running asynchronous operation
  float result = await DoLotsOfDataManipulationInTheBackend();
  
  // convert the results to a currency string based on the culture set previously
  string value = result.ToString(“C”);
}

Asynchronous operations need a thread to run, and these threads come from a thread pool created by the class library. This pool is then ready for use by your .NET application. Now, there's a small problem: while a thread awaits another operation to complete, the rest of the method's code might be executed in the context of a different thread.

Can you spot the potential problem? Since the above code sets the current thread's culture before awaiting for a method to complete, the "ToString" method call at the end might have a totally different thread than the beginning of the method.

This sounds like a big problem, and it could be, if you are using an older .NET framework version. Exactly said, .NET framework versions before version 4.6 can have issues in preserving the thread's current culture between different async/await calls. But, this issue has been fixed in .NET 4.6. Says the documentation:

"For apps that target the .NET Framework 4.6 or later versions, culture is part of an asynchronous operation's context. In other words, 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."

So, if you use .NET 4.6 or later, you're safe.

Happy hacking!