18.5. Storing Thread-Specific Data Privately
Problem
You want to store thread-specific data discovered at runtime. This data should be accessible only to code running within that thread.
Solution
Use the AllocateDataSlot, AllocateNamedDataSlot, or GetNamedDataSlot method on the Thread class to reserve a thread local storage (TLS) slot. Using TLS, a large object can be stored in a data slot on a thread and used in many different methods. This can be done without having to pass the structure as a parameter.
For this example, a class called ApplicationData here represents a set of data that can grow to be very large in size:
public class ApplicationData
{
// Application data is stored here.
}Before using this structure, a data slot has to be created in TLS to store the class. GetNamedDataSlot is called to get the appDataSlot. Since that doesn't exist, the default behavior for GetNamedDataSlot is to just create it. The following code creates an instance of the ApplicationData class and stores it in the data slot named appDataSlot:
ApplicationData appData = new ApplicationData();
Thread.SetData(Thread.GetNamedDataSlot("appDataSlot"), appData);Whenever this class is needed, it can be retrieved with a call to Thread.GetData. The following line of code gets the appData structure from the data slot named appDataSlot:
ApplicationData storedAppData =
(ApplicationData)Thread.GetData(Thread.GetNamedDataSlot("appDataSlot"));At this point, the storedAppData structure can be read or modified. After ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access