Initializing ThreadStatic fields
May 17th, 2008 at 1:23 pm by stjYesterday a friend of mine came across a problem concerning the initialization of ThreadStatic fields. He always encountered a NullReferenceException while accessing those fields.
Here's a sketch of what he tried to do:
-
class Program
-
{
-
[ThreadStatic]
-
-
static void Main(string[] args)
-
{
-
t1.Start();
-
t2.Start();
-
}
-
-
void RunThread()
-
{
-
Console.WriteLine(Program.aValue.ToString());
-
}
-
-
}
Everytime the program executed RunThread() the NullReferenceException has been raised. Therefore the question was why the field aValue didn't get initialized.
As usally a note at .Net Framework Reference has an answer to this question:
Do not specify initial values for fields marked with ThreadStaticAttribute, because such initialization occurs only once, when the class constructor executes, and therefore affects only one thread. If you do not specify an initial value, you can rely on the field being initialized to its default value if it is a value type, or to a null reference (Nothing in Visual Basic) if it is a reference type.
So, next question: How to initialize ThreadStatic fields?
We decided to encapsulate the initialization in a property:
-
class Program
-
{
-
[ThreadStatic]
-
static StringBuilder aValue;
-
-
static StringBuilder AValue
-
{
-
get
-
{
-
if (null == aValue)
-
return aValue;
-
}
-
}
-
-
static void Main(string[] args)
-
{
-
t1.Start();
-
t2.Start();
-
}
-
-
void RunThread()
-
{
-
Console.WriteLine(Program.AValue.ToString());
-
}
-
-
}