Thursday, March 12, 2009

Thread-specific data and the FreeNamedDataSlot function

First a bit of “context” setting before we proceed. If you’ve ever wanted to store data that is local to a single thread, you have three alternatives depending on your environment. If you’re only inside of a HTTP Web Request, you are in luck as you can set data into the HttpContext.Current.Items and its good for the duration of that web request.

If you happen to be writing any other type of application (Console, Windows Forms, Windows Service, etc…) then you have two alternatives. The easiest is to make a field with the ThreadStaticAttribute. You use this on a static field. With this attribute each thread has its own version of the field. That’s pretty easy!

If you want a little more control (or headaches) then you can use the Thread.GetNamedDataSlot and the Thread.GetData/Thread.SetData methods. What do all these do? Well, GetNamedDataSlot looks for a data slot on the current thread with the name that you pass to the method. If no slot is found it lazily instantiates one for you. The value returned is used as an argument to the GetData and the SetData methods, in other words your getter and setter for accessing thread local data.

BEWARE: There is another static method named FreeNamedDataSlot which you should use with extreme caution or not at all. This will free all of the data slots from each and every thread! The only time this makes sense to use is when you are absolutely sure that there are no threads running that are making use of the named slot you are about to free.

Technorati Tags: ,

No comments:

Post a Comment