system.net.mail.smtpclient
有两种我很困惑的方法。
1 . SendAsync(MailMessage,对象)
将指定的电子邮件消息发送到 SMTP 服务器进行传送。此方法不会阻塞调用线程,并允许调用者将对象传递给操作完成时调用的方法。 -MSDN
2 . SendMailAsync(MailMessage)
将指定的消息发送到 SMTP 服务器以作为异步操作进行传递。 -MSDN
请注意,两个方法的名称不同,因此它不是重载。这里到底有什么区别?
我正在寻找非常明确的答案,因为 MSDN 对这两种方法的描述非常模糊(至少对我来说是这样。)
区别在于,一个
SendMailAsync
使用新的async/await
技术,另一个使用旧的回调技术。更重要的是,当方法完成时,传递的 Object
会作为 userState
简单地传递到事件处理程序中。
首先,它们都是异步工作的。
但是,
SendAsync
自.NET 2以来就已存在。为了保持向后兼容性,同时支持新的任务系统,添加了SendMailAsync
。
SendMailAsync
返回 Task
而不是 void
,并允许 SmtpClient
支持新的 async
和 await
功能(如果需要)。
//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; }
}
}
}