Wednesday, October 22, 2008

Storing Information Per Thread

I recently ran across a situation where I wanted to store information per Thread. After doing some research I ran across the ThreadStaticAttribute class. You apply this attribute to a static field and the value for the variable is unique for each thread. Also note that a default value is useless since it will only be initialized once and the following threads will just have a null value. So, it is best to apply this attribute to a private field and have a public property that can initialize if needed.

private static string myThreadValue;

public static string MyThreadValue
if (myThreadValue == null)
myThreadValue = "New value";
return myThreadValue;

There are other methods to store data per thread. One is SetData / GetData methods on the class System.Runtime.Remoting.Messaging.CallContext. This method allows you to specify a named variable and a value. The reason I don't like this approach is that it doesn't allow you to strongly type the data since the SetData / GetDat use a Object parameter.

Finally, the Thread.AllocateDataSlot method allows you to create a "storage slot" and use the Thread.SetData and Thread.GetData to you to store information. The reason I don't like this approach is the same as mentioned above about the lack of strong typing. Secondly, this method is is slower than the ThreadStaticAttribute.

1 comment: