所以GC.Collect()似乎没有在调试模式下工作 [英] GC.COllect() doesnt seem to work in debug mode

查看:142
本文介绍了所以GC.Collect()似乎没有在调试模式下工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我运行下面的code和结果是完全不同的,当它运行在发行模式。虽然在调试模式下,它永远不会收集A类的对象,并在Reaelse模式下,它会立即收集类A的对象。

有人能解释这是为什么。

 使用系统;
使用System.Collections.Generic;
使用System.Linq的;
使用System.Text;

命名空间ConsoleApplication2 {
    类节目
    {
        静态无效的主要(字串[] args)
        {
            一个OBJ =新的A();

            乙BOBJ = obj.objB;

            所以GC.Collect();
            GC.WaitForPendingFinalizers();

            而(bobj.isLive)
            {
                Console.WriteLine(还活着!);
            }

            Console.WriteLine(是死的!);

            到Console.ReadLine();
        }
    }

    A类:IDisposable的

    {
        公众B objB =新的B();

        公开发行A()
        {}

        〜A()
        {
            objB.Dispose();
        }

        #地区IDisposable的成员

        公共无效的Dispose()
        {
            GC.Sup pressFinalize(本);
        }

        #endregion


    }
    B类:IDisposable的
    {
        公共BOOL将isLive = TRUE;

        #地区IDisposable的成员

        公共无效的Dispose()
        {
            this.isLive = FALSE;
            GC.Sup pressFinalize(本);
        }

        #endregion
    }}
 

解决方案

在调试模式下,编译器不优化局部变量。因此,引用仍然存在。在释放模式中,编译器优化的使用,使得参考被丢弃并且该对象可以被收集。

I am running the code below and the result is totally different when it runs in Release mode. While in Debug mode, it never collects the object of class A and in Reaelse mode it immediately collects the object of class A.

Can someone explain why.

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text;

namespace ConsoleApplication2 {
    class Program
    {
        static void Main(string[] args)
        {
            A obj = new A();

            B bobj = obj.objB;

            GC.Collect();
            GC.WaitForPendingFinalizers();

            while (bobj.isLive)
            { 
                Console.WriteLine("Is Alive!!");
            }

            Console.WriteLine("Is Dead!!");

            Console.ReadLine();
        }
    }

    class A:IDisposable

    {
        public B objB = new B();

        public A()
        { }

        ~A()
        {
            objB.Dispose();   
        }

        #region IDisposable Members

        public void  Dispose()
        {
            GC.SuppressFinalize(this);
        }

        #endregion


    }
    class B:IDisposable
    {
        public bool isLive = true;

        #region IDisposable Members

        public void  Dispose()
        {
            this.isLive = false;
            GC.SuppressFinalize(this);
        }

        #endregion
    } }

解决方案

In Debug mode, the compiler does not optimize the local variables. Therefore, the reference to A still exists. In Release mode, the compiler optimized the usage so that the reference is thrown away and the object can be collected.

这篇关于所以GC.Collect()似乎没有在调试模式下工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆