I have a very old but very large library which I am considering converting to a C# class library. The existing library uses a lot of global variables stored in the TLS. C# h
There are three main methods for allowing the thread to exclusively access its own version of thread-unsafe object.
1- [ThreadStatic]
The implementation is super easy and, it can be done through signing a static field with [ThreadStatic]
attribute
[ThreadStatic] static int y;
Now each thread then sees a separate copy of y;
unfortunately, [ThreadStatic]
doesn't work with instance fields.
2- ThreadLocal
It is new to framework 4.0
and it provides thread-local storage for both static and instance fields.
also, you can provide default value per each thread and that value is evaluated lazily.
static ThreadLocal y = new ThreadLocal (() => 10); //Static variable
ThreadLocal y = new ThreadLocal (() => 10); //Instance variable
3- GetData and SetData
In this approach, two methods of Thread
class are using: GetData
and SetData
.
These methods store data in thread-specific "Slots". A name should be specified for the
slot, so the same slot can be used across all threads and they will get separate values.
// The same LocalDataStoreSlot object can be used across all threads.
LocalDataStoreSlot y= Thread.GetNamedDataSlot ("slotName");
object data = Thread.GetData (y);
Thread.SetData (y, value)