Dispose SmtpClient in SendComplete?

两盒软妹~` 提交于 2019-12-09 03:01:19

问题


When I use SmtpClient's SendAsync to send email, how do I dispose the smtpclient instance correctly?

Let's say:


MailMessage mail = new System.Net.Mail.MailMessage()
{
   Body = MailBody.ToString(),
   IsBodyHtml = true,
   From = new MailAddress(FromEmail, FromEmailTitle),
   Subject = MailSubject
};
mail.To.Add(new MailAddress(i.Email, ""));
SmtpClient sc = new SmtpClient(SmtpServerAddress);
//Add SendAsyncCallback to SendCompleted
sc.SendCompleted += new SendCompletedEventHandler(SendAsyncCallback);
//using SmtpClient to make async send (Should I pass sc or mail into SendAsyncCallback?)
sc.SendAsync(mail, sc);

In the SendAsyncCallback method, should I call sc.Dispose(), or mail.Dispose()?

I checked MSDN document, one example calls MailMessage.Dispose(), but will this dispose method also dispose the SmtpClient instance?

Many Thanks.


回答1:


You should dispose both the MailMessage and the SmtpClient in SendAsyncCallback.

Disposing the MailMessage will not dispose the SmtpClient automatically (because you might want to send two messages with the same SmtpClient, and you wouldn't want the client to be disposed as soon as you disposed the first message).




回答2:


This example: from the MSDN Library documentation only closes the Message so I'm going with that in my implementation: SmtpClient.SendAsync Method

message.Dispose();

I was running into this issue referred to in this question where the send was always being cancelled so I'm removing my using {} statement: SmtpClient.SendAsync Calls are Automatically Cancelled

Okay, I just tried issuing the message.Dispose() and even that was throwing the error saying it couldn't send the email because of the message being disposed. Possibly because mine is a asp.net mvc app and the example is a console app. In any case the garbage collector should pick up these options once everything falls out of scope...



来源:https://stackoverflow.com/questions/5660353/dispose-smtpclient-in-sendcomplete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!