Repository navigation
ThreadIsolatedReference
Home > References > ThreadIsolatedReference
The ThreadIsolatedReference is somewhat similar to the ThreadLocal introduced in .Net 4.0 although it has some behavioral differences and can be used in .Net 3.5. Like a ThreadLocal it provides a thread safe reference where each thread has a completely isolated reference.
One of the key differences between this and a ThreadLocal is that this permits the initialization function which is used to populate the reference the first time a thread accesses the reference to be changed on the fly.
This class can only be used with non-nullable types, for nullable types use the ThreadIsolatedValue instead.
The API is relatively simple, a ThreadIsolatedReference may be created with or without an initializer function:
//No initializer function, reference will default to null
ThreadIsolatedReference<String> ref = new ThreadIsolatedReference<String>();
//Use an initializer function
ref = new ThreadIsolatedReference<String>(() => String.Empty);The value can then be accessed using the Value property:
//Get the value
String value = ref.Value;
//Set the value
ref.Value = "example";You can change the initializer function at any time like so:
//Set the initializer function
ref.Initialiser = () => "Default Value";