相关疑难解决方法(0)

正确使用IDisposable接口

我从阅读MSDN文档中了解到,IDisposable接口的"主要"用途是清理非托管资源.

对我来说,"非托管"意味着数据库连接,套接字,窗口句柄等等.但是,我已经看到了Dispose()实现该方法以释放托管资源的代码,这对我来说似乎是多余的,因为垃圾收集器应该照顾那对你而言.

例如:

public class MyCollection : IDisposable
{
    private List<String> _theList = new List<String>();
    private Dictionary<String, Point> _theDict = new Dictionary<String, Point>();

    // Die, clear it up! (free unmanaged resources)
    public void Dispose()
    {
        _theList.clear();
        _theDict.clear();
        _theList = null;
        _theDict = null;
    }
Run Code Online (Sandbox Code Playgroud)

我的问题是,这是否使得垃圾收集器可以使用的内存MyCollection比通常更快?

编辑:到目前为止,人们已经发布了一些使用IDisposable清理非托管资源(例如数据库连接和位图)的好例子.但是假设_theList在上面的代码中包含了一百万个字符串,并且你想现在释放那个内存,而不是等待垃圾收集器.上面的代码会实现吗?

.net c# garbage-collection idisposable

1586
推荐指数
12
解决办法
31万
查看次数

我什么时候应该创建一个析构函数?

例如:

public class Person
{
    public Person()
    {
    }

    ~Person()
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

我什么时候应该手动创建析构函数?什么时候需要创建析构函数?

c# destructor

177
推荐指数
4
解决办法
12万
查看次数

标签 统计

c# ×2

.net ×1

destructor ×1

garbage-collection ×1

idisposable ×1