为什么要使用gc.collect()? [英] Why should use gc.collect () ?

查看:94
本文介绍了为什么要使用gc.collect()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这样的程序中使用了析构函数



I had used destructor in program like this

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

namespace destructors
{
    class Program
    {
        int i = 5;
        public Program()
        {
            Console.WriteLine("Object created");
        }
        ~Program()
        {
            Console.WriteLine("Object destroyed");
        }
        static void Main(string[] args)
        {
            Program p = new Program();
            Console.WriteLine(p.i);
            p = null;
            GC.Collect();
            Console.ReadLine();
        }
    }
}







以上程序我已经使用GC.collect来销毁对象,但每当分配



p = null然后p对象内存释放为什么要专门使用GC.collect()。什么



是目的GC.collect()。如果在程序中使用p = null,它是强制性的。



谢谢你。



帮帮我。



我的尝试:



在上面的程序中我曾使用GC.collect来销毁对象但是无论何时分配



p = null然后是p对象memory deallocate为什么要特别使用GC.collect()。什么



是目的GC.collect()。如果在程序中使用p = null,它是强制性的。




in above program i had used GC.collect for destroy the object but whenever assign

p=null then p object memory deallocate why should use specifically GC.collect().what

is purpose GC.collect().is it mandatory if p=null use in program.

Thank u.

help me.

What I have tried:

in above program i had used GC.collect for destroy the object but whenever assign

p=null then p object memory deallocate why should use specifically GC.collect().what

is purpose GC.collect().is it mandatory if p=null use in program.

推荐答案

你通常永远不需要调用GC.Collect()。



它的唯一用途就是如果你真的知道你在做什么,你为什么这样做,愈伤组织的后果它,通常是因为内存限制你的代码放在系统上,这是非常罕见的。



在上面的例子中使用它只是为了演示物体寿命。普通代码中不需要它。
You normally never need to call GC.Collect().

It's only use is if you REALLY know what you're doing, why you're doing it, the consequences of calling it, and usually because of memory constraints your code is placing on the system, which is exceedingly rare.

It's use in the above example is just for a demonstration of object lifetime. It's not required in normal code.


1)p = null语句不取消分配对象内存。一旦执行了这个语句,p引用就不再指向它之前指向的Program类对象了。



2)de配置将发生或我说Memory占用的程序类当下次调用GC时,堆中的对象将被释放。



而GC.Collect将立即发生第2点。



如果我错了,请纠正我。希望这可以帮助。享受学习:)
1) p=null statement doesn't de-allocates the object memory. Once this statement is executed p reference no more points to the Program class object it was pointing earlier.

2) De allocation will happen or I say Memory occupied by Program class object in the heap will be released when GC is called next time.

And GC.Collect will make point 2 happen immediately.

Please correct me if I am wrong any where. Hope this helps. Enjoy learning :)


这篇关于为什么要使用gc.collect()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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