我从阅读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在上面的代码中包含了一百万个字符串,并且你想现在释放那个内存,而不是等待垃圾收集器.上面的代码会实现吗?
我最近遇到过Dispose方法必须在C#程序中进行硬编码的情况.否则,电子邮件中使用的文件将"永久"锁定,甚至进程管理器也无法告诉我锁定它的人/锁定了什么.我不得不使用Unlocker Assistant强制删除文件,但我担心现在我在服务器上留下了一些已分配的内存块.
我指的代码是这样的:
MailMessage mail = new MailMessage();
mail.From = new MailAddress("reception@domain.com", "###");
mail.Subject = "Workplace Feedback Form";
Attachment file = new Attachment(uniqueFileName);
mail.Attachments.Add(file);
mail.IsBodyHtml = true;
mail.CC.Add("somebody@domain.com");
mail.Body = "Please open the attached Workplace Feedback form....";
//send it
SendMail(mail, fldEmail.ToString());
Run Code Online (Sandbox Code Playgroud)
上面的代码使文件不uniqueFileName被Attachment句柄锁定,我无法删除它,因为这段代码是从客户端机器(而不是从服务器本身)运行的,所以无法找到该文件的句柄.
在我强制删除文件之后,我从另一个论坛发现我应该有Disposed of Attachment对象.
所以我在发送电子邮件后添加了这些代码行...
//dispose of the attachment handle to the file for emailing,
//otherwise it won't allow the next line to work.
file.Dispose();
mail.Dispose(); //dispose of the email object itself, but …Run Code Online (Sandbox Code Playgroud)