何时使用Dispose或何时使用Using

Fan*_*o68 1 c# asp.net dispose using handles

我最近遇到过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 not necessary really
File.Delete(uniqueFileName);  //delete the file 
Run Code Online (Sandbox Code Playgroud)

我应该把它包装在一份using声明中吗?

这就是我的问题的症结所在.我们何时应该使用Using以及何时应该使用Dispose?我希望两者之间有一个明确的区别,即如果你做"X"然后使用它,否则使用它.

这个什么时候配置?并且这个C#Dispose:当处置它并且处理它时我确实回答了我的问题,但我仍然对何时使用它们的"条件"感到困惑.

Igo*_*gor 6

using 在C#中:

using(MyDisposableType obj = new MyDisposableType())
{
  ...
}
Run Code Online (Sandbox Code Playgroud)

是"语法糖"(或简写符号),相当于

MyDisposableType obj = new MyDisposableType();
try {
  ...
} finally {
  obj.Dispose();
}
Run Code Online (Sandbox Code Playgroud)

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


D S*_*ley 5

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

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

using只需用更少的代码安全地实现该Dispose模式。 using将放入Dispose一个finally块中,以便即使抛出异常也可以处理该对象。按照现在的方式,如果抛出异常,对象将不会被释放,而是在垃圾收集时被清理。

我从未遇到过无法使用using必须手动使用try/finally的情况Dispose()

所以选择是你的——你可以Dispose在一个finally块中使用它,它可能和你使用的一样using