4

I'm considering making use of an HttpModule for localization purposes (based on the example in this article) - but I'm curious, is this safe?

Here's the code, for reference:

public class CookieLocalizationModule : IHttpModule
{
    public void Dispose()
    {
    }

    public void Init(HttpApplication context)
    {
        context.BeginRequest += new EventHandler(context_BeginRequest);
    }

    void context_BeginRequest(object sender, EventArgs e)
    {
        // eat the cookie (if any) and set the culture
        if (HttpContext.Current.Request.Cookies["lang"] != null)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies["lang"];
            string lang = cookie.Value;
            var culture = new System.Globalization.CultureInfo(lang);
            // is it safe to do this in all situations?
            Thread.CurrentThread.CurrentCulture = culture;
            Thread.CurrentThread.CurrentUICulture = culture;
        }
    }
}

I was under the impression that multiple threads could potentially service a web request. Is it safe to set the Current/Current UI Cultures in an HttpModule like this and have it respected for the life of the web request regardless of how many threads are involved in servicing it?

Update:

I have been using this method in production for nearly a year now, so I can certainly verify that it is perfectly safe to use an HttpModule for localization.

DanP
  • 6,310
  • 4
  • 40
  • 68

1 Answers1

2

Yes, this should be fine.

Im pretty sure that only one thread will service a request, unless you explicitly start another, and in that case, the culture (and other things) are copied to the other thread.

TimC
  • 1,051
  • 9
  • 16
  • Can you cite a source for "the culture (and other things) are copied to the other thread"? – DanP Feb 10 '11 at 14:10
  • I read it in Jeffrey Richters CLR via C# 3. I dont have it with me at the mo, so i cant verify 100% for you. When a thread creates a new thread, it copies over its context to the new thread. this includes the culture. If you call existing threads, inc threadpool threads, it may be different. – TimC Feb 10 '11 at 14:35