views:

797

answers:

3

After my application creates a thread using a ParameterizedThreadStart delegate, that thread performs some initialization and runs to completion. Later on, I can observe that this thread is no longer active because its IsAlive property is false and ThreadState property is ThreadState.Stopped.

Once a thread reaches this state they remain in my application, still existing as thread objects until my application shuts down. Are there any steps I can take to dispose of them once they're no longer active? I would like to delete the object and deallocate any resources so that any given moment the only thread objects I have are active threads. Thread doesn't implement IDisposable, though, so I'm not sure how I should do this.

+1  A: 

Your holding onto the reference to the thread in your code.

If you have written code that will check the state of the thread, then that code inherently will keep the thread object alive until the GC collects it.

Once you are finished with a thread, or ideally if you don't need to access it, make sure you null all references to it. Thread doesn't implement IDisposable because as you've made clear this wouldn't make sense for a thread.

Threads are native in .Net so you don't have to worry about leaks. If you're certain they will stop then just delete them from your list once you are sure it has finished.

Spence
I thought this might be the case, so I did my best to delete all references to the object. Using the VS debugger I checked the state of the thread periodicaly, and it remained a valid thread object. I suppose this means I'm still referencing it somewhere?
Chris Stevens
once the debugger is attached, the GC will not touch the object :(
Spence
+1  A: 

It sounds like you need to let go of your reference to the Thread object, so the garbage collector can discard it. Just set the reference you have to null, and let the GC do its job when it's ready.

Depending on your situation, you may wish to use a WeakReference (or my friend Cyrus' WeakReference<T>).

Jay Bazuzi
A: 

Is the unmanaged thread still there, did the thread actually return from its ParameterizedThreadStart method? Also try making IsBackground = false

Mo Flanagan