Sunday, July 8, 2012

Static is as static does, initializing ThreadStatic variables

I found the need to create some thread static variables using the ThreadStaticAttribute today in C#. In a hurry, I figured I would initialize them with a value.

  [ThreadStatic]
  private static string __host = "localhost";
  [ThreadStatic]
  private static int __port = 30000;

On the second thread call to the class I found that __host and __port were default values again. Curious I decided to take a look at the compiler generated code and found:

static MyObject()
{
    __host = "localhost";
    __port = 0x7530;
}

Why? The attribute is telling the runtime how share the variable and the language is telling the compiler how to create the IL.

Easy so initialize them in the instance level constructor right? No. That would overwrite the thread static variable every time the class is created. Best solution I found was to use nullable values and GetValueOrDefault.


  private const string DefaultHost = "localhost";
  private const int DefaultPort = 30000;
  [ThreadStatic]
  private static string __host;
  [ThreadStatic]
  private static int? __port;
//...//
  public string Host
  {
   get
   {
    return String.IsNullOrEmpty(__host) ? DefaultHost : __host;
   }
   set
   {
    __host = value;
   }
  }

  public int Port
  {
   get
   {
    return __port.GetValueOrDefault(DefaultPort);
   }
   set
   {
    __port = value;
   }
  }