在对象上调用.Dispose()方法有助于垃圾回收吗? [英] Calling .Dispose() method on objects helps in Garbage Collection?

查看:89
本文介绍了在对象上调用.Dispose()方法有助于垃圾回收吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在对对象调用.Dispose()方法,它对垃圾回收有帮助吗?
请在下面找到一个例子;

I am Calling .Dispose() method on objects, does it helps in Garbage Collection?
Please find an example below;

DataSet recordSet=null;
try
{
    ... //connection, command and adapter realated statements.
    adapter.Fill(recordSet);
    return recordSet;
}
catch (Exception ex)
{
    throw;
}
finally
{
    if (recordSet!=null)
    {
        recordSet.Dispose();
    }
    recordSet=null;
    GC.Collect();
    GC.Collect(2);
}

推荐答案

垃圾回收最好留给其自己的设备使用,请勿尝试使用GC.Collect对其进行强制.

Dispose并不能真正帮助垃圾回收,但是可以通过在垃圾回收之前释放非托管资源来实现垃圾回收.

using语句会为您完成所有这些异常操作.
Garbage collection is best left to its own devices, don''t try to coerce it with GC.Collect.

Dispose doesn''t really help with garbage collection, but it does help by releasing unmanaged resources before they get GCed.

A using statement does all that exception stuff for you btw.


这篇关于在对象上调用.Dispose()方法有助于垃圾回收吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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