C# how to correctly dispose of an SmtpClient?

后端 未结 6 1120
小鲜肉
小鲜肉 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:58

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

    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.

    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(); 
        }
    }
    

提交回复
热议问题