Welcome to OGeek Q&A 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...