static void Main(string[] args)
{
    //TestOperator();
    MemoryTest obj = new MemoryTest();
    obj = null;
    GC.Collect();
    GC.WaitForFullGCComplete();
    Console.ReadKey();
}public class MemoryTest : IDisposable
{
    public MemoryTest()
    {
        Console.WriteLine("MemoryTest.Construct called.");
    }    public void Dispose()
    {
        Console.WriteLine("MemoryTest.Dispose called.");
    }
}为什么不执行Dispose?

解决方案 »

  1.   

    IDisposable接口是为了让用户明白这个类中有需要即时释放的非托管资源,垃圾回收的时候不执行这个方法
      

  2.   

            public class MemoryTest : IDisposable
            {
                public MemoryTest()
                {
                    Console.WriteLine("MemoryTest.Construct called.");
                }            public void Dispose()
                {
                    Console.WriteLine("MemoryTest.Dispose called.");
                }            ~MemoryTest()
                {
                    Console.WriteLine("in finalizer");
                }
            }
            static void Main(string[] args)
            {
                for (Int32 i = 0; i < 100; i++)
                {
                    MemoryTest obj = new MemoryTest();
                    obj = null;
                    GC.Collect();
                }
                
                GC.WaitForFullGCComplete();
                Console.ReadKey();
             }
      

  3.   

    你在析构函数中写了就会自动执行的~~~~
    ~public MemoryTest()
    {
       Dispose();
    }
      

  4.   

    正确实现 IDisposable 接口
      

  5.   

    意思是,系统不会主动的调用Dispose方法?如果忘记调用,就资源泄漏了?
      

  6.   

    http://tech.e800.com.cn/articles/2009/112/1257126207415_1.html
      

  7.   

    http://tech.e800.com.cn/articles/2009/112/1257126207415_1.html
      

  8.   

    GC的是.NET中对内存管理的一种功能。垃圾回收器跟踪并回收托管内存中分配的对象,定期执行垃圾回收以回收分配给没有有效引用的对象的内存。当使用可用内存不能满足内存请求时,GC会自动进行。
    托管代码的堆上的垃圾内存可由GC自动回收,非托管代码中堆上的垃圾内存必须程序员自己负责释放、回收
    在.NET的对象中实际上有两个用于释放资源的函数:Dispose和Finalize。Finalize的目的是用于释放非托管的资源,而Dispose是用于释放所有资源,包括托管的和非托管的。
      

  9.   

    另一个问题,请移步到这里,顺带也看看。也是垃圾回收的问题。
    http://topic.csdn.net/u/20100727/15/bae88ccb-620e-4dca-ad90-d06d7f43741f.html?seed=1305171008&r=67274599#r_67274599
      

  10.   

    IDispose的作用在试用using(){}的时候比较明显,否则你得自己显式调用