[ThreadStatic]
private static string myThreadValue;
public static string MyThreadValue
{
get
{
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.
Interesting -- nice find.
ReplyDelete