I have a class that uses the Thread class:
class A
{
public Thread thread
{ get; set; }
}
Should I implement IDisposable and set Thread property to null?
class A : IDisposable
{
public Thread Thread
{ get; set; }
protected bool Disposed
{ get; set; }
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!this.Disposed)
{
if (disposing)
{
if (Thread != null)
Thread = null;
}
Disposed = true;
}
}
}
Or not?
Why?
You implement
IDisposableonly when your class is handling an unmanaged object, resources or otherIDisposableobjects. A Thread is not an unmanaged object and will get garbage collected when nothing is referencing it or when the process handling it is terminated. Since Thread is not implementingIDisposable, your class referencing it does not need to implement it either.Optionally, for
IDisposablewithin the scope of a method, they can be wrapped in ausingstatement and the Dispose() method is automatically called when the scope is exited.