views:

153

answers:

4

We have a system that runs in IIS.

The system should always run using the same "culture", but we cannot rely on the server settings being set correct.

One way to do it is to specify the culture everytime we do a ToString.

However, we were wondering, is it possible to set the culture on a thread at the begining of a method and rely on all the code in that method being run on the same thread?

+3  A: 

If you know you want the culture to stay the same for all threads, then that should be a fine approach.

However, if you need to set the culture on, say, a per-request basis that may be different from one request to the next, that can potentially not be a reliable approach. Under high load, we have seen threads reused for multiple requests and requests migrated from one thread to another, leaving their culture (and other threadstatic info) behind.

Rex M
+1 Thanks for the answer
Shiraz Bhaiji
Is it really possible that within a single method block, there is a thread change ?
Manitra Andriamitondra
+3  A: 

No. ASP.NET exhibits thread agility - in some situations, the request may move from one thread to another at specific points in its request lifecycle. (It's not "just anywhere"; this blog post gives more specific details.)

Unfortunately this isn't as clearly documented as it might be, and it's relatively hard to provoke - so you can easily get into the situation where under test loads, all is fine - but in production things go wrong.

However, some tests I ran a while ago (look for "jskeet" within the page) suggests that Thread.CurrentCulture is preserved even when thread agility kicks in.

Jon Skeet
I am wondering wow this is affected if you have web gardening turned off?
Chris Ballance
Absolutely no idea, I'm afraid...
Jon Skeet
+1 Thanks for the answer
Shiraz Bhaiji
+2  A: 

Do you dynamically change the culture? If not, you can set the culture in the web.config file.

<system.web>
  <globalization culture="ja-JP" uiCulture="zh-HK" />
</system.web>

You can also set it at page level:

<%@Page Culture="fr-FR" Language="C#" %>

And on the thread:

Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE");

But for what you are using, the page-level or web.config level seems like the most appropriate perhaps.

Sohnee
+1  A: 

As others pointed out, ASP.NET might decide to process parts of the same request in different threads. However, you are talking about initializing thread-static stuff at the beginning of each method, so this restriction does not apply to you: I'm quite sure that ASP.NET cannot change the current thread in the middle of one of your methods, so your approach should be fine.

Heinzi
+1 Thanks for the answer
Shiraz Bhaiji