VS 2010代码分析报告如下:
警告4 CA2000:Microsoft.Reliability:在方法 'Mailer.SendMessage()' 中,对象 'client' 沿所有异常路径未被处理。在所有引用超出作用域之前,请调用 System.IDisposable.Dispose 对象“client”。
我的代码是:
public void SendMessage()
{
SmtpClient client = new SmtpClient();
client.Send(Message);
client.Dispose();
DisposeAttachments();
}
如何正确处理客户端?
更新:为了回答Jon的问题,这里是处理附件函数的代码:
private void DisposeAttachments()
{
foreach (Attachment attachment in Message.Attachments)
{
attachment.Dispose();
}
Message.Attachments.Dispose();
Message = null;
}
Last Update 全课程清单(非常简短)
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;
}
}