system.net.mail.smtpclient
有两种方法我很困惑。
1。 SendAsync(MailMessage,Object)
Sends the specified e-mail message to an SMTP server for delivery. This method does not block the calling thread and allows the caller to pass an object to the method that is invoked when the operation completes.
-MSDN
2。的 SendMailAsync(MAILMESSAGE)
Sends the specified message to an SMTP server for delivery as an asynchronous operation.
-MSDN
请注意,两种方法的名称不同,因此不是过载。这有什么区别?
我正在寻找非常明确的答案,因为MSDN对这两种方法的描述非常模糊(至少对我来说是这样。)
答案 0 :(得分:27)
差异是一个SendMailAsync
使用新的async/await
技术而另一个使用旧的回调技术。更重要的是,当方法完成时,传递的Object
只是作为userState
传递给事件处理程序。
答案 1 :(得分:7)
首先,它们都是异步工作的。
但是,自{2}以来,SendAsync
已存在。为了保持向后兼容性,同时支持新的任务系统SendMailAsync
已添加。
SendMailAsync
返回Task
而不是void
,并允许SmtpClient
支持新的async
和await
功能,如果需要的话。 / p>
答案 2 :(得分:0)
SendMailAsync
SendAsync
的简单TAP包装器
更多信息:Are the SmtpClient.SendMailAsync methods Thread Safe?
答案 3 :(得分:0)
//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; }
}
}
}