Slightly off-topic: You can use Tasks instead of naked threads to run functions without worrying about disposal.
There are multiple issues here:
- Setting the variable to null doesn't delete anything, it simply removes a reference to your instance.
- The destructor will only get called when the garbage collector decides to collect your instance. The garbage collector runs infrequently, typically only when it detects that there is memory pressure.
- The garbage collector collects ONLY orphaned collections. Orphaned means that any references pointed to by your object are invalid.
You should implement the IDisposable interface and call any cleanup code in the Dispose method. C# and VB offer the using
keyword to make disposal easier even in the face of exception.
A typical IDisposable implementation is similar to the following:
class MyClass:IDisposable
{
ClassB _otherClass;
...
~MyClass()
{
//Call Dispose from constructor
Dispose(false);
}
public void Dispose()
{
//Call Dispose Explicitly
Dispose(true);
//Tell the GC not call our destructor, we already cleaned the object ourselves
GC.SuppressFinalize(this);
}
protected virtual Dispose(bool disposing)
{
if (disposing)
{
//Clean up MANAGED resources here. These are guaranteed to be INvalid if
//Dispose gets called by the constructor
//Clean this if it is an IDisposable
_otherClass.Dispose();
//Make sure to release our reference
_otherClass=null;
}
//Clean UNMANAGED resources here
}
}
You can then use your class like this :
using(var myClass=new MyClass())
{
...
}
Once the using
block terminates, Dispose() will be called even if an exception occurs.