asp.net 这两种方法有什么区别?

68bkxrlz  于 2023-01-22  发布在  .NET
关注(0)|答案(4)|浏览(182)

system.net.mail.smtpclient有两个方法,我对此感到非常困惑。
1 .异步发送(邮件、对象)
将指定的电子邮件发送到SMTP服务器进行传递。此方法不阻止调用线程,并允许调用方将对象传递给操作完成时调用的方法。-MSDN
2 .异步发送邮件(邮件)
将指定的邮件发送到SMTP服务器以作为异步操作进行传递。-MSDN

注意两个方法的名称不同,所以它不是重载。这里的区别到底是什么?

我正在寻找非常明确的答案,因为MSDN对这两种方法的描述都非常模糊(至少对我来说是这样)

ux6nzvsh

ux6nzvsh1#

区别在于一个SendMailAsync使用新的async/await技术,另一个使用旧的回调技术,更重要的是,当方法完成时,传递的Object只是作为userState传递到事件处理程序中。

wgxvkvu9

wgxvkvu92#

首先,它们都异步工作。
但是,SendAsync自.NET 2以来就已存在。为了在支持新任务系统的同时保持向后兼容性,添加了SendMailAsync
SendMailAsync返回Task而不是void,并允许SmtpClient在需要时支持新的asyncawait功能。

7xllpg7q

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; }
        }
    }
}
zujrkrfu

zujrkrfu4#

SendMailAsyncSendAsync的简单TAP Package 器更多信息:Are the SmtpClient.SendMailAsync methods Thread Safe?

相关问题