Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C# have a "ThreadLocal" analog (for data members) to the "ThreadStatic" attribute?

I've found the "ThreadStatic" attribute to be extremely useful recently, but makes me now want a "ThreadLocal" type attribute that lets me have non-static data members on a per-thread basis.

Now I'm aware that this would have some non-trivial implications, but:

Does such a thing exist already built into C#/.net? or since it appears so far that the answer to this is no (for .net < 4.0), is there a commonly used implementation out there?

I can think of a reasonable way to implement it myself, but would just use something that already existed if it were available.

Straw Man example that would implement what I'm looking for if it doesn't already exist:

class Foo
{
    [ThreadStatic] 
    static Dictionary<Object,int> threadLocalValues = new Dictionary<Object,int>();
    int defaultValue = 0;

    int ThreadLocalMember
    {
         get 
         { 
              int value = defaultValue;
              if( ! threadLocalValues.TryGetValue(this, out value) )
              {
                 threadLocalValues[this] = value;
              }
              return value; 
         }
         set { threadLocalValues[this] = value; }
    }
}

Please forgive any C# ignorance. I'm a C++ developer that has only recently been getting into the more interesting features of C# and .net

I'm limited to .net 3.0 and maybe 3.5 (project has/will soon move to 3.5).

Specific use-case is callback lists that are thread specific (using imaginary [ThreadLocal] attribute) a la:

class NonSingletonSharedThing
{
     [ThreadLocal] List<Callback> callbacks;

     public void ThreadLocalRegisterCallback( Callback somecallback )
     {    
         callbacks.Add(somecallback);    
     }

     public void ThreadLocalDoCallbacks();
     {    
         foreach( var callback in callbacks )  
            callback.invoke();  
     }
}

1 Answers

Enter .NET 4.0!

If you're stuck in 3.5 (or earlier), there are some functions you should look at, like AllocateDataSlot which should do what you want.

like image 122
Travis Gockel Avatar answered Sep 15 '25 07:09

Travis Gockel