首页 > 解决方案 > 在返回语句之前未等待异步承诺

问题描述

昨天有这个问题,改了一些代码,又出现了……为什么两个邮件都不发送?没有等待承诺。有时会发送 1 封邮件,有时会发送 2 封邮件。Bool "messagesSent" 有时也会返回 false,而它应该返回 true。

功能:

private async Task<bool> SendMails(string email, string name, string pdfPath, string imgPath)
{
    var client = new SendGridClient(_config["SendGrid:Key"]);
    bool messagesSent = false;
    try
    {
        var messageClient = new SendGridMessage
        {
            From = new EmailAddress(_config["SendGrid:Recipient"]),
            Subject = "Subject1",
            HtmlContent = _textManager.Get("email-b")
        };

        var MessageServer = new SendGridMessage
        {
            From = new EmailAddress(_config["SendGrid:Recipient"]),
            Subject = "Subject2",
            HtmlContent = _textManager.Get("email-s")
        };

        messageClient.AddTo(email, name);
        MessageServer.AddTo(email, name);

        string[] fileListClient = new string[] { pdfPath };
        string[] FileListServer = new string[] { pdfPath, imgPath };

        foreach (var file in fileListClient)
        {
            var fileInfo = new FileInfo(file);

            if (fileInfo.Exists)
                await messageClient.AddAttachmentAsync(fileInfo.Name, fileInfo.OpenRead());
        }

        foreach (var file in FileListServer)
        {
            var fileInfo = new FileInfo(file);

            if (fileInfo.Exists)
                await MessageServer.AddAttachmentAsync(fileInfo.Name, fileInfo.OpenRead());
        }

        var responseClient = await client.SendEmailAsync(messageClient);
        var responseServer = await client.SendEmailAsync(MessageServer);

        if (responseClient.StatusCode.ToString() == "202" && responseServer.StatusCode.ToString() == "202")
        {
            messagesSent = true;
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
    }
    return messagesSent;
}

调用者:

                bool sentMails = await SendMails(formCollection["email"], formCollection["name"], pdfPath, imgPath);

                if (!sentMails)
                {
                    errorMessage = "Error sending mails.";
                    succes = false;
                }

编辑: 请求有效,呼叫被 ISP/MailServer 阻止。这与错误的异步无关。

标签: c#.netasynchronousasync-awaitsendgrid

解决方案


Ok, the whole point of an asynchroneous call, is not to "wait" or delay performance. The method will just 'run'. Unless there is an exception raised in that method, there is nothing that would prevent the method from not get executed successfully.

Try adding a break-point and see why the messagesSent returns false sometimes, I am suspecting this line:

if (responseClient.StatusCode.ToString() == "202" && responseServer.StatusCode.ToString() == "202")

Is there any chance that the StatusCode might be returning a "200" as well?


推荐阅读