Sohan's Blog

Things I'm Learning

[ThreadStatic] - a Cool Attribute to Thread Safe Static Members

Usually static variables holds the same value for all the threads running at the same AppDommain. However, in a multithreaded scenario, you may need to add thread safe behavior to your static members so that the value of a static member is same inside only a single thread and across multiple threads the value can be different. In this way you may attain a thread specific or thread scoped storage to use in your application. One example is, in Log4Net you need to use ThreadContext class to store the values to be logged that are thread specific.

.Net framework has a smart and easy way of achieving it through the use of ThreadStaticAttribute class. When you apply this attribute to your static members, it will take care of the thread safety. So, from a sample C# code like the following one, you may define thread safe static members.