Is it possible to cache the result of the GetNamedDataSlot function (and reuse it for all threads), or should it be called in / for each thread?
Unfortunately, at this stage, the documentation is not 100% understandable. Some interesting places include & hellip;
From Thread.GetNamedDataSlot (String) Method :
Data slots are unique to each stream. No other thread (even a child thread) can receive this data
And from the LocalDataStoreSlot Class :
Data slots are unique to each stream or context; their values are not shared between stream or context objects.
At best, they make it clear that each thread gets its own copy of the data. But passes can be considered meaning that LocalDataStoreSlot itself is a stream, or just the data to which it refers refers to streams. I believe this is the last, but I can’t point to a specific MSDN page that says so.
So, we can see the implementation details :
Each process has one slot manager, which is used to support all the slots for each thread. A LocalDataStoreSlot returned in one thread can be transferred to another thread and used there, and it will belong to the same manager and use the same slot index (since the slot table is also per-process). It also happens that the Thread.SetData() method will implicitly create a local thread data store for this slot, if it does not already exist.
The Thread.GetData() method simply returns null if you have not set a value yet, or if a local thread data store has not been created. Thus, the behavior of GetData() remains consistent regardless of whether you have already called SetData() on this thread.
Since slots are process-level controlled, you can reuse LocalDataStoreSlot values for streams. After allocation, the slot is used for all streams, and the data stored for this slot will be unique for each stream. Sharing the LocalDataStoreSlot value in streams shares this slot, but even for one slot you get a local stream store for each stream.
In fact, looking at it that way, the implementation you are showing would be a desirable way to use this API. After all, this is an alternative to [ThreadStatic] , and the only way to provide a different LocalDataStoreSlot value for each thread in your code is to either use [ThreadStatic] (which, if you wanted to use it, you should just use it for the data itself) or to maintain your own a dictionary of LocalDataStoreSlot values indexed presumably using Thread.ManagedThreadId .
Personally, I just use [ThreadStatic] . MSDN even recommends this, and it has clearer semantics of IMHO. But if you want to use LocalDataStoreSlot , it seems to me that your implementation is correct.