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

后端 未结 5 1157
陌清茗
陌清茗 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:55

    Note: .NET 4.5 SmtpClient implements async awaitable method SendMailAsync. For lower versions, use SendAsync as described below.


    You should always dispose of IDisposable instances at the earliest possibility. In the case of async calls, this is on the callback after the message is sent.

    var message = new MailMessage("from", "to", "subject", "body"))
    var client = new SmtpClient("host");
    client.SendCompleted += (s, e) => {
                               client.Dispose();
                               message.Dispose();
                            };
    client.SendAsync(message, null);
    

    It's a bit annoying the SendAsync doesn't accept a callback.

提交回复
热议问题