
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Storing Thread-Specific Data Privately
|
1039
Discussion
Thread local storage is a convenient way to store data that is usable across method
calls without having to pass the structure to the method or even without knowledge
about where the structure was actually created.
Data stored in a named TLS data slot is available only to that thread; no other thread
can access a named data slot of another thread. The data stored in this data slot is
accessible from anywhere within the thread. This setup essentially makes this data
global to the thread.
To create a named data slot, use the static
Thread.GetNamedDataSlot method. This
method accepts a single parameter,
name, that defines the name of the data slot. This
name should be unique; if a data slot with the same name exists, then the contents of
that data slot will be returned and a new data slot will not be created. This action
occurs silently; there is no exception thrown or error code available to inform you
that you are using a data slot someone else created. To be sure that you are using a
unique data slot, use the
Thread.AllocateNamedDataSlot method. This method
throws a
System.ArgumentException if a data slot already exists with the same name.
Otherwise, it operates similarly to the
GetNamedDataSlot method.
It is interesting to note that this ...