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 ...
Get C# Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.