Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

wpf - In .Net: best way for keeping CurrentCulture on new Thread?

In a .Net 4.0 WPF project, we need to keep the same CurrentCulture on each thread then we have on the main thread.

Given, we can initialize a new thread's culture with code like the following:

  1. Keep the information in a variable (context)

    context.CurrentCulture = Thread.CurrentThread.CurrentCulture;
    context.CurrentUICulture = Thread.CurrentThread.CurrentUICulture;
    
  2. On the new thread, initialize from the saved context

    Thread.CurrentThread.CurrentCulture = context.CurrentCulture;
    Thread.CurrentThread.CurrentUICulture = context.CurrentUICulture;
    

But in this age of TPL, async programming and lambda delegates, it does not feel right.

And yes, we actually can change the culture while the application is running, but that is another story.

Do you know of any setting, property or config we should initialize to keep track?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There is no good way, avoid this at all cost. The fundamental problem is that culture is not part of the Thread.ExecutionContext, it doesn't flow from one thread to another. This is a unsolvable problem, culture is a property of a native Windows thread. It will always be initialized to the system culture as selected in Control Panel's Region and Language applet.

Making temporary thread-local changes to the culture is fine, trying to switch 'the process' to another culture is a source of bugs you'll be hunting for months. The string collation order is the nastiest source of problems.


EDIT: this problem was fixed in .NET 4.5 with the CultureInfo.DefaultThreadCurrentCulture and DefaultThreadCurrentUICulture properties.


EDIT: and got the real solution in .NET 4.6, culture now flows from one thread to another. Check the MSDN article for CultureInfo.CurrentCulture for details. Beware that the description does not quite match behavior, testing required.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...