What are best practices for using SmtpClient, SendAsync and Dispose under .NET 4.0

后端 未结 5 1147
陌清茗
陌清茗 2020-11-28 02:19

I\'m a bit perplexed on how to manage SmtpClient now that it is disposable, especially if I make calls using SendAsync. Presumably I should not call Dispose until SendAsync

5条回答
  •  离开以前
    2020-11-28 02:44

    In general, IDisposable objects should be disposed as soon as possible; implementing IDisposable on an object is intended to communicate the fact that the class in question holds expensive resources that should be deterministically released. However, if creating those resources is expensive and you need to construct a lot of these objects, it may be better (performance wise) to keep one instance in memory and reuse it. There's only one way to know if that makes any difference: profile it!

    Re: disposing and Async: you can't use using obviously. Instead you typically dispose the object in the SendCompleted event:

    var smtpClient = new SmtpClient();
    smtpClient.SendCompleted += (s, e) => smtpClient.Dispose();
    smtpClient.SendAsync(...);
    

提交回复
热议问题