我最近遇到了必须在 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 它确实回答了我的问题,但我仍然对何时使用任何一个的“条件”感到困惑。