Thread Local Storage For C# Class Library

There are the ThreadLocal class (introduced in 4.0) and the ThreadStaticAttribute.

The ThreadStaticAttribute can be used only on static fields. The ThreadLocal class can be used on "normal" fields but it is slower.

Be aware that if you don't control the thread you are on (for example you are a page of ASP.NET and you start on a "random" pre-used thread, or you are a thread of a ThreadPool), then your "thread-static" (in general, not the attribute) variables will be pre-initialized with the old values of the previous thread. (see for example A tale of two techniques: The [ThreadStatic] Attribute and System.Web.HttpContext.Current.Items)

I was forgetting, there is the Thread.AllocateDataSlot that has similar "objectives" than the others.


Presuming you're going to use .NET 4.0, you could have a static ThreadLocal<ThreadLocalData> where your ThreadLocalData class has all your variables as properties:

class ThreadLocalData
{
    public int GlobalInt { get; set; }
    public string GlobalString { get; set; }
}

class Global
{
    static ThreadLocal<ThreadLocalData> _ThreadLocal =
        new ThreadLocal<ThreadLocalData>( () => new ThreadLocalData() );

    public static ThreadLocalData ThreadLocal
    {
       get { return _ThreadLocal.Value; }
    }
}

You would then access the properties like this:

int i = Global.ThreadLocal.GlobalInt;

You could add any global variables that are not thread-local as normal properties of the Global class.


You can achieve the same thread local storage using the [ThreadStatic] attribute or in .Net 4 by using the ThreadLocal class.

[ThreadStatic]    
private static string MyThreadGlobal;

private ThreadLocal<string> MyThreadGlobal = new ThreadLocal<string>();

There's also the CallContext class but the other approaches are probably preferred.