如何让SendGrid无阻塞地运行?

时间:2016-08-04 02:02:18

标签: asp.net-mvc sendgrid

这是我的代码

public static void sendEmail(string sendto, string subject, string template, Object model)
{
    SendGridAPIClient sg = new SendGridAPIClient(ConfigurationManager.AppSettings["SendGridAPIKey"]);
    Email from = new Email(ConfigurationManager.AppSettings["EmailSender"]);
    Email to = new Email(sendto);
    var templateFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "EmailTemplates");
    var tpl = File.OpenText(templateFolder + "\\" + template).ReadToEnd();
    string textbody = Engine.Razor.RunCompile(tpl, template, null, model);
    Content content = new Content("text/plain", textbody);
    Mail mail = new Mail(from, subject, to, content);
    dynamic response = sg.client.mail.send.post(requestBody: mail.Get());
}

在许多地方调用此函数。如何在不阻止调用此函数的多个位置的情况下运行此函数?

1 个答案:

答案 0 :(得分:0)

您可以使用HostingEnvironment.QueueBackgroundWorkItem

using System.Web.Hosting;

HostingEnvironment.QueueBackgroundWorkItem((ct) => sendEmail(sendto, subject, template, model));