关于c#:何时使用Dispose或何时使用Using

When to use Dispose or when to use Using

我最近遇到一种情况,必须在C#程序中对Dispose方法进行硬编码。否则,电子邮件中使用的文件将被"永远"锁定,甚至Process Manager也无法告诉我谁/什么锁定了它。我不得不使用Unlocker Assistant强制删除文件,但是我担心现在我已经在服务器上留下了一些分配的内存块。

我指的代码是这样的:

1
2
3
4
5
6
7
8
9
10
11
MailMessage mail = new MailMessage();
mail.From = new MailAddress("[email protected]","###");
mail.Subject ="Workplace Feedback Form";
Attachment file = new Attachment(uniqueFileName);
mail.Attachments.Add(file);
mail.IsBodyHtml = true;
mail.CC.Add("[email protected]");
mail.Body ="Please open the attached Workplace Feedback form....";

//send it
SendMail(mail, fldEmail.ToString());

上面的代码使文件uniqueFileName中的文件被附件句柄锁定,我无法删除它,并且由于此代码是从客户端计算机(而不是服务器本身)运行的,因此无法找到文件的句柄。

强制删除文件后,我从另一个论坛发现应该删除附件对象。

所以我在发送电子邮件后添加了这些代码行...

1
2
3
4
5
6
//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 not necessary really
File.Delete(uniqueFileName);  //delete the file

我应该将其包装在using语句中吗?

这就是我的问题的症结所在。我们什么时候应该使用Using以及何时应该使用Dispose?我希望两者之间有明确的区别,即如果您执行" X",则使用此选项,否则请使用。

这什么时候处置?和这个C#Dispose:何时处置以及由谁处置确实可以回答我的问题,但是我仍然对何时使用两者的"条件"感到困惑。


C#中的using

1
2
3
4
using(MyDisposableType obj = new MyDisposableType())
{
  ...
}

是等价的"语法糖"(或简称)

1
2
3
4
5
6
MyDisposableType obj = new MyDisposableType();
try {
  ...
} finally {
  obj.Dispose();
}

如http://msdn.microsoft.com/en-us//library/yh598w02.aspx中所述


Should I have wrapped this in a using statement instead?

要么将主代码放入try块中,然后将Dispose放入finally块中。

using只需较少的代码即可安全地实现Dispose模式。 using会将Dispose放在finally块中,以便即使抛出异常也可以处置对象。 您现在所拥有的方式(如果引发异常)将不会处理对象,而是在收集垃圾时将其清除。

我从未遇到无法使用using的情况,而必须手动将try / finallyDispose()一起使用。

因此,选择就是您自己-您可以在finally块中使用Dispose,并且可能与使用using相同。