Using Managed Thread Local Storage

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”);

Thread.SetData(dataSlot, someVariable);

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:

Thread.FreeNamedDataSlot(“DATA1”);

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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.