我可以从普通的同步方法中调用等待的异步方法吗?

时间:2020-08-25 18:59:53

标签: c# asp.net

我在ASP.net中有发送电子邮件的代码。我的应用程序使用ASP.net Webforms较旧,并且未转换为异步方法。

但是,可以等待通过SendGrid发送电子邮件的方法。

如果我使用放弃,Visual Studio不会抱怨:

_  = SendASendGridMessage()

如果执行此操作,是否会导致崩溃或死锁?

这是示例代码:

public static void SendNew(string toEmail, string subject, string htmlContent, int domainId, int partyId, string category, int itemId)
{           
    EmailAddress from = new EmailAddress("example@example.com");
    EmailAddress to = new EmailAddress(toEmail);
    EmailAddress replyTo = new EmailAddress("example@example.com");
            
    htmlContent = $"<html><body>{htmlContent}</body></html>";           

    var msg = MailHelper.CreateSingleEmail(from, to, subject, null, htmlContent);

    _ = SendASendGridMessage(msg, domainId);
}

// Which will then connect with this method later:

// Summary:
// Make a request to send an email through Twilio SendGrid asynchronously.
//
// Parameters:
//   msg:
//     A SendGridMessage object with the details for the request.
//
//   cancellationToken:
//     Cancel the asynchronous call.
//
// Returns:
//     A Response object.
[AsyncStateMachine(typeof(<SendEmailAsync>d__23))]
public Task<Response> SendEmailAsync(SendGridMessage msg, CancellationToken cancellationToken = default);

2 个答案:

答案 0 :(得分:-1)

您可以使用“即弃即用”方法,就像您一样,在不使用await的情况下调用异步方法。实际上,分离耗时的操作(例如从处理http请求的代码发送电子邮件)是一个好习惯。您需要记住的一件事是,ASP.NET Web应用程序被视为无状态,并且主机可以随时决定卸载您的应用程序,甚至在异步方法完成之前。

ASP.NET Framework中有一种机制,可以安排长时间的活动,以便主机可以正常终止您的应用程序,以等待安排的活动

HostingEnvironment.QueueBackgroundWorkItem

using System.Web.Hosting;

...

// Schedule task in a background tread 
Func<CancellationToken, Task> workItem = ct => SendASendGridMessage(...);
HostingEnvironment.QueueBackgroundWorkItem(workItem);

答案 1 :(得分:-2)

您可以使用以下内容:

Task t = new Task(() =>
  {
    if (something == true) 
    {
        DoSomething(e);  
    }
  });
  t.RunSynchronously();

有关更多详细信息,请参见以下主题:

Synchronously waiting for an async operation, and why does Wait() freeze the program here