Sets the data in the specified slot on the currently running thread, for that thread's current domain. For better performance, use fields marked with the ThreadStaticAttribute attribute instead.
- slot
- The LocalDataStoreSlot in which to set the value.
- data
- The value to be set.
The .NET Framework provides two mechanisms for using thread local storage (TLS): thread-relative static fields (that is, fields that are marked with the ThreadStaticAttribute attribute) and data slots. Thread-relative static fields provide much better performance than data slots, and enable compile-time type checking. For more information about using TLS, see Thread Local Storage: Thread-Relative Static Fields and Data Slots.
Threads use a local store memory mechanism to store thread-specific data. The common language runtime allocates a multi-slot data store array to each process when it is created. The thread can allocate a data slot in the data store, store and retrieve a data value in the slot, and free the slot for reuse after the thread procedure ends and the System.Threading.Thread object has been reclaimed by garbage collection. Data slots are unique per thread. No other thread (not even a child thread) can get that data.
Thread.SetData(LocalDataStoreSlot, object) is a Shared method that always applies to the currently executing thread, even if you call it using a variable that refers to another thread. To avoid confusion, use the class name when calling Shared methods: Thread.SetData(testSlot, "test data").