C# how to correctly dispose of an SmtpClient?

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

    The SmtpClient class in .NET 4.0 now implements IDisposable, while the SmtpClient class in .NET 2.0 lacks this interface (as Darin noted). This is a breaking change in the framework and you should take appropriate actions when migrating to .NET 4.0. However, it is possible to mitigate this in your code before migrating to .NET 4.0. Here is an example of such:

    var client = new SmtpClient();
    
    // Do not remove this using. In .NET 4.0 SmtpClient implements IDisposable.
    using (client as IDisposable)
    {
        client.Send(message);
    } 
    

    This code will compile and run correctly both under .NET 2.0 (+3.0 and 3.5) and under .NET 4.0.

提交回复
热议问题