September 20, 2008 Leave a comment
It happens so many times that you come to access a static member from different threads to find it null although you have added the [ThreadStatic] attribute to your object initialization.
I have created a sample code to illustrate what is the problem and what causes it.
First, I created a dummy class called person that I am going to use in my test application:
public class Person
name = "person";
public string name;
So now suppose I have a another test class that looks as follows:
public class Test
private static Person _person = new Person();
public void Run()
Thread p1 = new Thread(PrintPersonName);
Thread p2 = new Thread(PrintPersonName);
public void PrintPersonName()
What the class does here is that spawns two threads to print the person name. So you supposed the output to be :
However, what is going to really happen is that you are going to get only the first person printed and the second one you will get an ObjectRefernceException because you will find the person object to be null.
The secret behind that is that the C# compiler hoists the initialization of person into the Person’s static constructor. The static constructor is only executed just before the type is needed , and it’s only executed once. This means that the first thread to access the person object will initialize it and have a reference to it. However, other threads when try to access the person object, the constructor will not be called because it was called before and therefore, they will find it to be null. Microsoft has promised that they are going to introduce a solution for that issue with the next version of .Net FrameWork by introducing new types LazyInit<T>.