Because of the following information from microsoft, I updated my code a bit. It sounds like they updated the currentculture to something I could use.
For apps that target the .NET Framework 4.6 and later versions, CultureInfo.CurrentCulture and CultureInfo.CurrentUICulture are stored in a thread's ExecutionContext, which flows across asynchronous operations. (source: https://msdn.microsoft.com/en-us/library/dn833123(v=vs.110).aspx)
using System;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("start " + Thread.CurrentThread.CurrentCulture.ToString() + " " + Thread.CurrentThread.ManagedThreadId);
RunAsync().Wait();
Console.WriteLine("Finish " + Thread.CurrentThread.CurrentCulture.ToString() + " " + Thread.CurrentThread.ManagedThreadId);
Console.ReadKey();
}
static async Task RunAsync()
{
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("de-DE");
Console.WriteLine("1 " + Thread.CurrentThread.CurrentCulture.ToString() + " " + Thread.CurrentThread.ManagedThreadId);
string cultureInTask = string.Empty;
await Task.Run(() => cultureInTask = Thread.CurrentThread.CurrentCulture.ToString() + " " + Thread.CurrentThread.ManagedThreadId).ConfigureAwait(true);
Console.WriteLine("2 " + cultureInTask);
string twoA = await TestMethodAsync();
Console.WriteLine("2a " + twoA + " " + Thread.CurrentThread.ManagedThreadId);
Console.WriteLine("3 " + Thread.CurrentThread.CurrentCulture.ToString() + " " + Thread.CurrentThread.ManagedThreadId);
}
public static async Task<string> TestMethodAsync()
{
Console.WriteLine("2s " + Thread.CurrentThread.CurrentCulture.ToString() + " " + Thread.CurrentThread.ManagedThreadId);
return await Task.Run(() =>
{
return System.Threading.Thread.CurrentThread.CurrentUICulture.ToString() + " " + Thread.CurrentThread.ManagedThreadId;
});
}
}
Output:
start en-US 1
1 de-DE 1
2 de-DE 3
2s de-DE 3
2a en-US 4 4
3 de-DE 4
Finish en-US 1
But why is 2a returning en-US and not de-DE? Is it because the executionContext is different? If so, how can I stay in the same execution context?
CurrentCulture
and CurrentUICulture
are independent properties. You're only setting CurrentCulture
, and you're reporting that everywhere except for 2a, which reports CurrentUICulture
. If you use the same property consistently throughout the code (either property should be fine), it'll give you the expected results.
See more on this question at Stackoverflow