(Post 27/11/2007) Each thread gets a data store
isolated from all other threads. This is useful for storing "out-of-band"
data – that which supports the execution path's infrastructure, such as
messaging, transaction or security tokens. Passing such data around via
method parameters would be extremely clumsy and would alienate all but
your own methods; storing such information in static fields would mean
sharing it between all threads.
Thread.GetData reads from a thread's
isolated data store; Thread.SetData writes to it. Both
methods require a LocalDataStoreSlot object to identify
the slot – this is just a wrapper for a string that names the slot – the
same one can be used across all threads and they'll still get separate
values. Here's an example:
class ... {
// The same LocalDataStoreSlot object can be used across all threads.
LocalDataStoreSlot secSlot = Thread.GetNamedDataSlot ("securityLevel");
// This property has a separate value on each thread.
int SecurityLevel {
get {
object data = Thread.GetData (secSlot);
return data == null ? 0 : (int) data; // null == uninitialized
}
set {
Thread.SetData (secSlot, value);
}
}
...
Thread.FreeNamedDataSlot will release
a given data slot across all threads – but only once all LocalDataStoreSlot
objects of the same name have dropped out of scope and been garbage
collected. This ensures threads don't get data slots pulled out from under
their feet – as long as they keep a reference to the appropriate LocalDataStoreSlot
object for as long as it's in use.
(Sưu tầm) |