本文介绍了如何在Task.Run中调用异步方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以异步方式发送邮件.我已经弄清楚了要使用Razor Generator从razor视图生成HTML模板.现在我需要使用SmtpClient.SendMailAsync将HTML作为邮件发送.但是我发现Razor生成器要花很多时间,并且我不想在我的send mail方法中包括模板生成部分,因为send mail方法应该不关心获取HTML模板.

I need to send mail in Async way. I have figured out to use Razor Generator to generate Html template from razor view. now i need to use SmtpClient.SendMailAsync to send the html as Mail. but i found Razor generator takes quite some time and i do not want to include the template generation part inside my send mail method as the send mail method should not be concerned about getting the Html Template.

我有示例代码:

public static void SendEmailAsync<TModel>(TModel model, string templatePath, string subj, string toEmail, string cc = null, string bcc = null)
    {

        string templateFilePath = HostingEnvironment.MapPath(templatePath);
        // Generate the email body from the template file.
        // 'templateFilePath' should contain the absolute path of your template file.
        if (templateFilePath != null)
        {
            Task.Run(() =>
            {
                var emailHtmlBody = Engine.Razor.RunCompile(File.ReadAllText(templateFilePath),
                templateFilePath, model.GetType(), model);
                SendEmailAsync(subj, emailHtmlBody, toEmail, cc, bcc);
            });
        }
        else
        {
            throw new System.Exception("Could not find mail template.");
        }
    }

,SendMailAsync的签名为:

and the signature for SendMailAsync Is:

static async Task SendEmailAsync(string subj, string message, string toEmail, string cc = null, string bcc = null)
    {
        //Reading sender Email credential from web.config file
        string fromEmail = ConfigurationManager.AppSettings["FromEmail"].ToString();
        string fromName = ConfigurationManager.AppSettings["FromName"].ToString();

        //creating the object of MailMessage
        MailMessage mailMessage = new MailMessage();
        mailMessage.From = new MailAddress(fromEmail, fromName); //From Email Id
        mailMessage.Subject = subj; //Subject of Email
        mailMessage.Body = message; //body or message of Email
        mailMessage.IsBodyHtml = true;

        string[] toMuliId = toEmail.Split(',');
        foreach (string toEMailId in toMuliId)
        {
            mailMessage.To.Add(new MailAddress(toEMailId)); //adding multiple TO Email Id
        }


        if (cc != null)
        {
            string[] ccId = cc.Split(',');

            foreach (string ccEmail in ccId)
            {
                mailMessage.CC.Add(new MailAddress(ccEmail)); //Adding Multiple CC email Id
            }
        }

        if (bcc != null)
        {
            string[] bccid = bcc.Split(',');

            foreach (string bccEmailId in bccid)
            {
                mailMessage.Bcc.Add(new MailAddress(bccEmailId)); //Adding Multiple BCC email Id
            }
        }

        SmtpClient smtp = new SmtpClient
        {
            EnableSsl = true,
            Credentials = new NetworkCredential("", "")
        };

        //network and security related credentials
        await smtp.SendMailAsync(mailMessage); //sending Email
    }

没有引发异常,但我得到了错误:

No exceptions are thrown but i get the error:

推荐答案

使用此:

await Task.Run(async () =>
{
    await DoAsyncMethodAsync();
});

这篇关于如何在Task.Run中调用异步方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 18:08