Monday 28 March 2011

Dot.Net: Using Thread Local Storage

Question:
How to store and access thread specific static data in dot.net.
I want my static data not shared between different threads. How do I do this?



Answer:
This is called: using thread local storage (TLS)
You can either use the LocalDataStoreSlot or a static member with a ThreadStatic attribute.

Thread-relative static field perform much better, but you need to know at compile time what you want to store.
LocalDataStoreSlots can be created at runtime.

Store data in LocalDataStoreSlot
// allocate a named data slot
Thread.AllocateNamedDataSlot("myData");

// get slot by name and set data
LocalDataStoreSlot myData = Thread.GetNamedDataSlot("myData");
Thread.SetData(myData , 321);


later we wanna read the data

LocalDataStoreSlot myData = Thread.GetNamedDataSlot("myData");
int myValue = (int)Thread.GetData(myData);

// free the data slot.
Thread.FreeNamedDataSlot("myData");



Store data in ThreadStaticAttribute
A static field marked with ThreadStaticAttribute is not shared between threads.
Each thread sees a different field.


...
[ThreadStatic]
public static string value;
...

No comments: