system.net.mail.smtpclient有两个方法,我对此感到非常困惑。1 .异步发送(邮件、对象)将指定的电子邮件发送到SMTP服务器进行传递。此方法不阻止调用线程,并允许调用方将对象传递给操作完成时调用的方法。-MSDN2 .异步发送邮件(邮件)将指定的邮件发送到SMTP服务器以作为异步操作进行传递。-MSDN
system.net.mail.smtpclient
注意两个方法的名称不同,所以它不是重载。这里的区别到底是什么?
我正在寻找非常明确的答案,因为MSDN对这两种方法的描述都非常模糊(至少对我来说是这样)
ux6nzvsh1#
区别在于一个SendMailAsync使用新的async/await技术,另一个使用旧的回调技术,更重要的是,当方法完成时,传递的Object只是作为userState传递到事件处理程序中。
SendMailAsync
async/await
Object
userState
wgxvkvu92#
首先,它们都异步工作。但是,SendAsync自.NET 2以来就已存在。为了在支持新任务系统的同时保持向后兼容性,添加了SendMailAsync。SendMailAsync返回Task而不是void,并允许SmtpClient在需要时支持新的async和await功能。
SendAsync
Task
void
SmtpClient
async
await
7xllpg7q3#
//SendAsync public class MailHelper { public void SendMail(string mailfrom, string mailto, string body, string subject) { MailMessage MyMail = new MailMessage(); MyMail.From = new MailAddress(mailfrom); MyMail.To.Add(mailto); MyMail.Subject = subject; MyMail.IsBodyHtml = true; MyMail.Body = body; MyMail.Priority = MailPriority.Normal; SmtpClient smtpMailObj = new SmtpClient(); /*Setting*/ object userState = MyMail; smtpMailObj.SendCompleted += new SendCompletedEventHandler(SmtpClient_OnCompleted); try { smtpMailObj.SendAsync(MyMail, userState); } catch (Exception ex) { /* exception handling code here */ } } public static void SmtpClient_OnCompleted(object sender, AsyncCompletedEventArgs e) { //Get the Original MailMessage object MailMessage mail = (MailMessage)e.UserState; //write out the subject string subject = mail.Subject; if (e.Cancelled) { Console.WriteLine("Send canceled for mail with subject [{0}].", subject); } if (e.Error != null) { Console.WriteLine("Error {1} occurred when sending mail [{0}] ", subject, e.Error.ToString()); } else { Console.WriteLine("Message [{0}] sent.", subject); } } // } //SendMailAsync public class MailHelper { // public async Task<bool> SendMailAsync(string mailfrom, string mailto, string body, string subject) { MailMessage MyMail = new MailMessage(); MyMail.From = new MailAddress(mailfrom); MyMail.To.Add(mailto); MyMail.Subject = subject; MyMail.IsBodyHtml = true; MyMail.Body = body; MyMail.Priority = MailPriority.Normal; using (SmtpClient smtpMailObj = new SmtpClient()) { /*Setting*/ try { await smtpMailObj.SendMailAsync(MyMail); return true; } catch (Exception ex) { /* exception handling code here */ return false; } } } }
zujrkrfu4#
SendMailAsyncSendAsync的简单TAP Package 器更多信息:Are the SmtpClient.SendMailAsync methods Thread Safe?
4条答案
按热度按时间ux6nzvsh1#
区别在于一个
SendMailAsync
使用新的async/await
技术,另一个使用旧的回调技术,更重要的是,当方法完成时,传递的Object
只是作为userState
传递到事件处理程序中。wgxvkvu92#
首先,它们都异步工作。
但是,
SendAsync
自.NET 2以来就已存在。为了在支持新任务系统的同时保持向后兼容性,添加了SendMailAsync
。SendMailAsync
返回Task
而不是void
,并允许SmtpClient
在需要时支持新的async
和await
功能。7xllpg7q3#
zujrkrfu4#
SendMailAsync
SendAsync
的简单TAP Package 器更多信息:Are the SmtpClient.SendMailAsync methods Thread Safe?