I have a very old but very large library which I am considering converting to a C# class library. The existing library uses a lot of global variables stored in the TLS. C# h
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.