O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

15.12. Storing Thread-Specific Data Privately

Problem

You want to store thread-specific data discovered at runtime on a thread that will be accessible only to code running within that thread.

Solution

Use the AllocateDataSlot or AllocateNamedDataSlot method on the Thread class to reserve a thread local storage (TLS) slot. Using TLS, a large structure 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 structure called Data here represents a structure that can grow to be very large in size:

public struct Data
{
    // Application data is stored here
}

Before using this structure, a data slot has to be created in TLS to store the structure. The following code creates an instance of the Data structure and stores it in the data slot named AppDataSlot:

Data appData = new Data( );
Thread.SetData(Thread.GetNamedDataSlot("appDataSlot"), appData);

Whenever this structure 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:

Data storedAppData = (Data)Thread.GetData(Thread.GetNamedDataSlot("appDataSlot"));

At this point, the storedAppData structure can be read or modified. After the action has been performed on the storedAppData structure, storedAppData must be placed back into the data slot named appDataSlot:

Thread.SetData(Thread.GetNamedDataSlot("appDataSlot"), appData);

Once the application ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required