.netthreadstatic

.NET 4.0: How to clean up object references attributed as threadstatic after the thread as since exectured?


I have a static connection variable in an ASP.NET webform codebehind. In the page load event, I am executing several methods in separate threads. Each thread utilizes a threadstatic instance of this connection object. What I want to do is, in the page's dispose event, clean out all static instances of that one connection variable all at once. If this is not possible then I will just have to close the connections at the end of each method, but I'd like to handle it all in one line of code if possible.


Solution

  • It's not really possible to do in a single line of code. The page's Dispose event executes on a specific thread and hence only has access to one of the instances of the ThreadStatic value.

    You need to dispose of every instance at the conclusion of every created thread which utilizes the value.