Hello friend,
How to determine whether the object is recovered?
class Program{
static void Main(string[] args){
Student student = null;
using (student = new Student())
{
Console.WriteLine("student is null:{0}\n",student == null);
}
Console.WriteLine("student is null:{0}\n",student == null);
}}
public class Student : IDisposable
{
public Student() { }
~Student()
{
Console.WriteLine("Start Execute Destructor...\n");
}
public void Dispose(){
Console.WriteLine("Start Execute Dispose...\n");
}
}
Thanks.


VulpesRank #55 · 29.2K reputationPosted Mar 8, 2015, 3:28 PM EDT
So to release managed resources you'd set the corresponding fields to null. The GC will then clean them up in due course.
However, this will happen anyway when the object as a whole is garbage collected and so Dispose() is normally limited to cleaning up unmanaged resources (file handles, database connections etc.). The GC knows nothing about these and it's usually not enough to just garbage collect the managed wrapper - you need to specifically release the unmanaged resource to avoid a resource leak.
VulpesRank #55 · 29.2K reputationPosted Mar 7, 2015, 6:01 AM EST
However, if you do this, then you can also check in the destructor whether the object has already been disposed and, if it hasn't, call Dispose() before you execute the rest of the destructor code, if any. This is a useful precaution in case you (or your users) forget to call Dispose() yourself:
The output is:
Incidentally, there is not usually much point in releasing managed resources as these will be cleaned up automatically by the GC in any case. The main purpose of the IDispose pattern is to clean up unmanaged resources as the GC knows nothing about these.
Ken HRank #2,315 · 610 reputationPosted Mar 7, 2015, 4:19 PM EST
Ken HRank #2,315 · 610 reputationPosted Mar 8, 2015, 8:30 PM EDT