代码检查说我需要处理对象。哪一个?

时间:2011-06-24 20:40:29

标签: c# code-inspection

这是我的功能。我已将客户端和消息都包装到using子句中,并在运行代码检查时仍然出错。错误指向首先使用line:

public static void Send(MailItem mail)
        {
            var sender = Membership.GetUser(mail.CreatedBy);
            if (sender == null)
            {
                return;
            }

            using (var msg = new MailMessage { From = new MailAddress(ConfigurationManager.AppSettings["EmailSender"], ConfigurationManager.AppSettings["EmailSenderName"]) })
            {
                foreach (var recipient in mail.MailRecipients)
                {
                    var recipientX = Membership.GetUser(recipient.UserKey);
                    if (recipientX == null)
                    {
                        continue;
                    }

                    msg.To.Add(new MailAddress(recipientX.Email, recipientX.UserName));
                }

                msg.Subject = "[From: " + sender.UserName + "]" + mail.Subject;
                msg.Body = mail.Body;

                if (HttpContext.Current != null)
                {
                    msg.Body += Environment.NewLine + Environment.NewLine + "To reply via Web click link below:" +
                                Environment.NewLine;
                    msg.Body += ConfigurationManager.AppSettings["MailPagePath"] + "?AID=" +
                                ContextManager.CurrentAccount.AccountId + "&RUN=" + sender.UserName;
                }

                try
                {
                    using (var emailClient = new SmtpClient())
                    {
                        emailClient.Send(msg);
                    }
                }
                catch (Exception ex)
                {
                    Logger.LogException(ex);
                }
            }
        }

这是我得到的警告:

  

警告1 CA2000:   Microsoft.Reliability:方法   'Email.Send(MailItem)',对象   '<> g_ initLocal0'未被处置   沿着所有异常路径。呼叫   System.IDisposable.Dispose on object   毕竟'<> g _initLocal0'   对它的引用是出于   范围。 C:\ CodeWorkspace \ Code \ Utility \ Email.cs 41

1 个答案:

答案 0 :(得分:18)

你的问题就在这一行:

using (var msg = new MailMessage { From = new MailAddress(ConfigurationManager.AppSettings["EmailSender"], ConfigurationManager.AppSettings["EmailSenderName"]) }) 

初始化程序块{ From = ... }在构造对象之后和using块的内部try/finally开始之前执行。

如果MailAddress构造函数(或其参数表达式,或From的赋值(如果它是属性访问器))抛出异常,则MailMessage将不会被处理。

更改为:

using (var msg = new MailMessage()) 
{
    msg.From = new MailAddress(ConfigurationManager.AppSettings["EmailSender"], ConfigurationManager.AppSettings["EmailSenderName"]);
    ...
}

临时<>g_initLocal0变量是MailMessage在被分配到msg之前的名称。