C# how to correctly dispose of an SmtpClient?

后端 未结 6 1118
小鲜肉
小鲜肉 2020-12-05 12:57

VS 2010 code analysis reports the following:

Warning 4 CA2000 : Microsoft.Reliability : In method \'Mailer.SendMessage()\', object \'client\' is not disposed along

6条回答
  •  粉色の甜心
    2020-12-05 13:42

    This is the neater solution that will pass the code police test (and dispose will always be called if Send fails):

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

提交回复
热议问题