2

我最近遇到了必须在 C# 程序中硬编码 Dispose 方法的情况。否则,电子邮件中使用的文件将被“永远”锁定,甚至流程管理器也无法告诉我是谁/什么锁定了它。我不得不使用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());

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

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

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

//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 : when dispose 和 who dispose 它确实回答了我的问题,但我仍然对何时使用任何一个的“条件”感到困惑。

4

2 回答 2

7

using在 C# 中:

using(MyDisposableType obj = new MyDisposableType())
{
  ...
}

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

MyDisposableType obj = new MyDisposableType();
try {
  ...
} finally {
  obj.Dispose();
}

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

于 2014-03-28T01:55:06.850 回答
4

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

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

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

我从来没有遇到过我不能使用using并且必须手动使用try/ finallywith 的情况Dispose()

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

于 2014-03-28T01:55:28.557 回答