简体   繁体   English

C#asp.net从静态同步调用异步方法

[英]c# asp.net call async method from static sync

I call a static method named - validSendPass from ajax 我从ajax调用了一个名为validSendPass的静态方法

[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. 为此,我将smtp.Send替换为smtp.SendMailAsync或smtp SendAsync,添加异步。

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. 如果要使用异步,则需要使所有内容一直异步进行,以获取任何好处。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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