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.

VulpesPosted Mar 8, 2015, 7:28 PM
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.
Ken HPosted Mar 9, 2015, 12:30 AM
Ken HPosted Mar 7, 2015, 9:19 PM
VulpesPosted Mar 7, 2015, 11:01 AM
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.