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()); |
上面的代码使文件
强制删除文件后,我从另一个论坛发现应该删除附件对象。
所以我在发送电子邮件后添加了这些代码行...
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以及何时应该使用Dispose?我希望两者之间有明确的区别,即如果您执行" X",则使用此选项,否则请使用。
这什么时候处置?和这个C#Dispose:何时处置以及由谁处置确实可以回答我的问题,但是我仍然对何时使用两者的"条件"感到困惑。
C#中的
1 2 3 4 |
是等价的"语法糖"(或简称)
1 2 3 4 5 6 |
如http://msdn.microsoft.com/en-us//library/yh598w02.aspx中所述
Should I have wrapped this in a using statement instead?
要么将主代码放入
我从未遇到无法使用
因此,选择就是您自己-您可以在