相关疑难解决方法(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万
查看次数

在C#中"使用"有什么用处

用户kokos通过提及关键字回答了C#问题的精彩隐藏功能using.你能详细说明吗?有什么用using

c# using using-statement

301
推荐指数
11
解决办法
27万
查看次数