Best way to clear a value from a ThreadLocal<T>

I am using a ThreadLocal<T> to store an item-per-thread, but every soft often, I wish to clear a thread's stored value. How is the best way of doing this? I can reset the instance's value to null, but the IsValueCreated property still shows true.


var storage = new ThreadLocal<string>();
storage.Value = "hello";
//storage.IsValueCreated -> true
storage.Value = null;
//storage.IsValueCreated -> still true


You can't de-initialize the data for a single thread. There is no method to do it (other than recreating the ThreadLocal<>, losing all the values)

Once assigned, the value of IsValueCreated is true for that thread. null is a perfectly ok value, it doesn't mean "deassign the value" or "the value is not assigned".

"...the IsValueCreated property still shows true." - it is. You are set "Value = null" for current thread, but thread is still alive.

You should dispose the instance of ThreadLocal<string> and remove all references to it if you are done with it and create a new one.

The property Value is lazy initialized. So when you access the property for the first time, the value is created and the property IsValueCreated is set to true.

Need Your Help

How to use mysql_insert_id with a junction table

php mysql forms mysql-insert-id junction

I have a form and three tables: customer, phone_number, and junction (to create a many-to-many relationship).

Entity Framework Select with Include + Group By Count + Paging and Projection

linq entity-framework dto projection

I'm trying to do a query with EF6 that would eager load a related object then group it then count the total number of related records and do paging but so far i am not successful.