简体   繁体   中英

c# asp.net call async method from static sync

I call a static method named - validSendPass from ajax

[WebMethod]
public static string validSendPass(string em)

In this method I need create email class and call to method that send async my email

classes.email ems = new classes.email();
ems.sendPassword(myemail, my email name, user email, user name, password, "Your password", pas);

This method:

var fromAddress = new MailAddress(fromem, fromname);
var toAddress = new MailAddress(toem, toname);

var smtp = new SmtpClient
{
    Host = "smtp.gmail.com",
    Port = 587,
    EnableSsl = true,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    UseDefaultCredentials = false,
    Credentials = new NetworkCredential(fromAddress.Address, fromPassword),
    Timeout = 20000
};
using (var message = new MailMessage(fromAddress, toAddress)
{
    Subject = subject,
    Body = body
})
{
    try { smtp.Send(message); }
    catch { }
}

For this I replace smtp.Send to smtp.SendMailAsync or to smtp SendAsync, add the async.

How I need change this code - call async method from static method?

You can't . You're asking how to synchronously call an asynchronous method. If you make it synchronous then it is no longer asynchronous .

You can block the method until the asynchronous operation has completed, but if you do that then you'll have defeated the entire purpose of making the method asynchronous in the first place.

If you really need the end result to be synchronous, just leave everything synchronous from top to bottom, and don't use any asynchronous methods anywhere. If you're going to use asynchrony you need to make everything asynchronous, all the way up, for there to be any benefits.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM