ThreadLocal in combination with IHttpModule

75 Views Asked by At

I have been playing around in a webproject where I in a HttpModule would like to prepare some data the different classes on a later stage should work.

Would it be safe to expose that data in a public static accessable ThreadLocal storage?

ie.

public static ThreadLocal<A> storage = new ThreadLocal<A>();

private void Application_BeginRequest(Object source, EventArgs )
{
    storage.Value = new A();
}

My initial test shows that code executed in my controllers etc. actually works on the same thread as the above snippet from a module is executed in.

ie.

public ActionResult Index()
{
    var o = module.storage;
    if (o.IsValueCreated)
    {
        // WORX
    }
    return View();
}

But I could not find any documentation that ensured me this is a guaranteed behaviour.

Would this work? Or should I get this behaviour in an other way?

(Needless to say that any threads that I spin up myself on a later state would loose connection to the TLS.)

0

There are 0 best solutions below