At work we needed to keep information about each thread. Due to application’s nature we couldn’t know when a thread would call our code and to make things more interesting we couldn’t even rely on the thread id for unique identification.
Because of those restrains an external data structure was out of the question and we needed to find a way to store that data in the thread itself.
Luckily .NET Thread has the ability to store data on the thread itself using DataSlots:
To Save Data from sameVariable in the current thread local storage:
LocalDataStoreSlot dataSlot = Thread.oo(“DATA1”);
And then we can get that information by using:
LocalDataStoreSlot dataSlot = Thread.GetNamedDataSlot(“DATA1”);
string val = Thread.GetData(dataSlot).ToString();
And finally we need to release it:
It that simple. The only problem I found is that we can only set and get data from the current thread.
You can read more about it at msdn.