views:

166

answers:

3

I noticed that System.Threading.Thread implements a finalizer but not IDisposable. The recommended practice is to always implement IDisposable when a finalizer is implemented. Jeffrey Richter wrote that the guideline is "very important and should always be followed without exception".

So why doesn't Thread implement IDisposable? It seem like implementing IDisposable would be a non-breaking change that would allow deterministic cleanup of Thread's finalizable resources.

And a related question: since thread is finalizable, do I have to hold references to running Threads to prevent them from being finalized during execution?

+6  A: 

What would disposing of a Thread object do? The "resource" in this case has its own natural clean-up - the thread finishing. Note that also the sense of ownership is missing... within the executing thread, you can always use Thread.CurrentThread, so only that thread would really able to claim any sort of ownership.

Basically I think Thread is a slightly unusual case - there's a lifetime to the underlying resource, but it isn't something that ought to be cleaned up explicitly.

Jon Skeet
+1  A: 

That's probably because you can't dispose of a thread. Instead you can ask it to die using Abort() or alike.

Miguel Ventura
You can but in general the use of Abort is not considered good practice - just ensure the thread method returns (using a bool or similar) and the system clears up the rest.
Matt Breckon
+1  A: 

This is kind of a design question, so anyone who was not involved in building this aspect of .NET can only speculate. That being said, this blog post makes a good point:

...implementing IDisposable would not make any difference, at least in the current implementation of Thread. I increased the number of threads being created and the handle count goes down at some point so there is some mechanism for closing them

Threads do naturally clean up after themselves, so they are not a resource that needs to be managed in the typical sense.

Rex M