Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A list of all active ThreadLocal<T> and [ThreadStatic] references

How can I get a list of all references that are currently held in ThreadLocal or ThreadStatic storage?

I.e. all objects that cannot be garbage collected because some thread holds a reference to this object in its thread-local storage.

Can I use reflection to find those instances, or at least their total size, without knowing their names or types?

Or failing that, some way to show them in Visual Studio 2010? (I am looking for something besides a full-blown memory profiler)

My motivation is this: I just had a very nasty memory leak where the contents of a ConcurrentBag were held by various ThreadPool threads, even though the original ConcurrentBag had long been gone out of scope and garbage collected. Although I squashed this particular bug, I want to find out if there are more such bugs lurking around.

Ideally, I would like some way to periodically log the number of objects held by thread-local storage, and their size, at runtime.

like image 730
HugoRune Avatar asked Oct 30 '22 01:10

HugoRune


1 Answers

Unfortunately there is no way to do this.

you should instead make sure you clean up using IDisposable implementations and using(some IDisposable) where appropriate.

The framework itself does count references for you but there is no API to expose this information to the running code.

like image 76
War Avatar answered Nov 11 '22 08:11

War