Async Thread.CurrentThread.CurrentCulture in .net-4.6

Due to the following information from Microsoft, I have updated my code a bit. Looks like they updated the current culture to something I could use.

For applications targeting the .NET Framework 4.6 and later, CultureInfo.CurrentCulture and CultureInfo.CurrentUICulture are stored in the ExecutionContext thread, which flows through 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 to the US and not de-DE? Is it because executeContext is different? If so, how can I stay in the same execution context?

+3


source to share


1 answer


CurrentCulture

and CurrentUICulture

are independent properties. You install CurrentCulture

and you report that everywhere except 2a, which reports CurrentUICulture

. If you use the same property consistently throughout your code (or the property should be fine), it will give you the results you expect.



+2


source







All Articles