C# 如何正确处理 SmtpClient?

编程入门 行业动态 更新时间:2024-10-18 06:02:31
本文介绍了C# 如何正确处理 SmtpClient?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

VS 2010 代码分析报告如下:

VS 2010 code analysis reports the following:

警告 4 CA2000:Microsoft.Reliability:在方法 'Mailer.SendMessage()' 中,对象 'client' 并未沿所有异常路径处理.在对象client"的所有引用超出范围之前,调用 System.IDisposable.Dispose.

Warning 4 CA2000 : Microsoft.Reliability : In method 'Mailer.SendMessage()', object 'client' is not disposed along all exception paths. Call System.IDisposable.Dispose on object 'client' before all references to it are out of scope.

我的代码是:

public void SendMessage() { SmtpClient client = new SmtpClient(); client.Send(Message); client.Dispose(); DisposeAttachments(); }

我应该如何正确处理客户?

How should I correctly dispose of client?

更新:要回答 Jons 的问题,这里是处理附件功能:

Update: to answer Jons question, here is the dispose attachments functionality:

private void DisposeAttachments() { foreach (Attachment attachment in Message.Attachments) { attachment.Dispose(); } Message.Attachments.Dispose(); Message = null; }

最后更新完整课程列表(简短)

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net.Mail; public class Mailer { public MailMessage Message { get; set; } public Mailer(MailMessage message) { this.Message = message; } public void SendMessage() { using (SmtpClient client = new SmtpClient()) { client.Send(Message); } DisposeAttachments(); } private void DisposeAttachments() { foreach (Attachment attachment in Message.Attachments) { attachment.Dispose(); } Message.Attachments.Dispose(); Message = null; } }

推荐答案

public void SendMessage() { using (SmtpClient client = new SmtpClient()) { client.Send(Message); } DisposeAttachments(); }

这样,即使在 Send 方法调用期间抛出异常,客户端也会被处理.您应该很少需要显式调用 Dispose - 它应该几乎总是在 using 语句中.

That way the client will be disposed even if an exception is thrown during the Send method call. You should very rarely need to call Dispose explicitly - it should almost always be in a using statement.

但是,这里并不清楚附件是如何涉及的.你的类是否实现了 IDisposable 本身?如果是这样,那可能是处理可能是成员变量的附件的地方.如果您需要绝对确保它们在这里得到处理,您可能需要:

However, it's not clear how the attachments are involved here. Does your class implement IDisposable itself? If so, that's probably the place to dispose of the attachments which are presumably member variables. If you need to make absolutely sure they get disposed right here, you probably need:

public void SendMessage() { try { using (SmtpClient client = new SmtpClient()) { client.Send(Message); } } finally { DisposeAttachments(); } }

更多推荐

C# 如何正确处理 SmtpClient?

本文发布于:2023-11-24 04:41:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1624009.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:正确处理   SmtpClient

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!