Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resetting ThreadLocal<T> Value

Tags:

c#

.net-4.0

I initialize my ThreadLocal with a valueFactory Func.

I would also like to reset the Value back to null on occasion.

Perhaps I'm doing something wrong, but if I set my threadLocal.Value = null, it still seems to think that threadLocal.IsValueCreated == true.

How can I truly reset the threadlocal so that it will regenerate the Value lazily when it is asked for?

like image 286
Pedro Avatar asked Dec 09 '25 12:12

Pedro


1 Answers

Not that I'm aware of.

You could always make it a ThreadLocal<Lazy<T>>, and set it to a new Lazy<T> whenever you wanted to reset it. If this is something you use more than once, you might want to consider encapsulating it as a ResettableThreadLocal<T> or something like that.

like image 132
Jon Skeet Avatar answered Dec 11 '25 01:12

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!