C# 函数在等待异步完成之前返回

C# 函数在等待异步完成之前返回,c#,.net,asynchronous,async-await,sendgrid,C#,.net,Asynchronous,Async Await,Sendgrid,我正试图通过SendGrid API发送两封电子邮件。有时0发送,有时1发送,有时两者都发送。这项功能似乎并不等待承诺。如何修复它,使其始终发送两封电子邮件 我的函数如下所示: private async Task<bool> SendMails(string email, string name, string pdfPath, string imgPath) { var client = new SendGridClient(_config["SendGrid:Key"]

我正试图通过SendGrid API发送两封电子邮件。有时0发送,有时1发送,有时两者都发送。这项功能似乎并不等待承诺。如何修复它,使其始终发送两封电子邮件

我的函数如下所示:

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

    var messageSecondClient = new SendGridMessage
    {
        From = new EmailAddress(_config["SendGrid:Recipient"]),
        Subject = "Second Testmail",
        HtmlContent = _textManager.Get("getSecondMailHtml")
    };

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

    string[] fileListClient = new string[] { pdfPath };
    string[] fileListSecond = 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 fileListSecond)
    {
        var fileInfo = new FileInfo(file);

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

    var responseClient = await client.SendEmailAsync(messageClient);
    var responseSecond = await client.SendEmailAsync(messageSecondClient);

    if (responseClient.StatusCode.ToString() == "202" && responseSecond.StatusCode.ToString() == "202")
    {
        messagesSent = true;
    }
    return messagesSent;
}
private async Task SendMails(字符串email、字符串name、字符串pdfPath、字符串imgPath)
{
var client=newsendGridClient(_config[“SendGrid:Key”]);
bool messagesSent=false;
var messageClient=new SendGridMessage
{
From=新电子邮件地址(_config[“SendGrid:Recipient”]),
Subject=“Testmail”,
HtmlContent=\u textManager.Get(“getMailHtml”)
};
var messageSecondClient=new SendGridMessage
{
From=新电子邮件地址(_config[“SendGrid:Recipient”]),
Subject=“第二封测试邮件”,
HtmlContent=\u textManager.Get(“getSecondMailHtml”)
};
messageClient.AddTo(电子邮件,名称);
messageSecondClient.AddTo(电子邮件,名称);
字符串[]fileListClient=新字符串[]{pdfPath};
string[]fileListSecond=新字符串[]{pdfPath,imgPath};
foreach(fileListClient中的var文件)
{
var fileInfo=新文件信息(文件);
如果(fileInfo.Exists)
等待messageClient.AddAttachmentAsync(fileInfo.Name,fileInfo.OpenRead());
}
foreach(fileListSecond中的var文件)
{
var fileInfo=新文件信息(文件);
如果(fileInfo.Exists)
等待messageSecondClient.AddAttachmentAsync(fileInfo.Name,fileInfo.OpenRead());
}
var responseClient=await client.sendmailasync(messageClient);
var responseSecond=await client.sendmailasync(messageSecondClient);
if(responseClient.StatusCode.ToString()=“202”和&responseSecond.StatusCode.ToString()=“202”)
{
messagesSent=true;
}
返回消息sent;
}
我这样称呼它:

            Task<bool> sendMails = await Task.FromResult(SendMails(formCollection["email"], formCollection["name"], pdfPath, imgPath));

            if (!sendMails.Result)
            {
                errorMessage = "Error sending mails.";
            }
Task sendMails=wait Task.FromResult(sendMails(formCollection[“email”]、formCollection[“name”]、pdfPath、imgPath));
如果(!sendMails.Result)
{
errorMessage=“发送邮件时出错。”;
}

您正在阻止异步任务:

if (!sendMails.Result)
这个可以。使用
wait
代替阻塞

您还可以取消
等待任务。FromResult
,它:


Task.FromResult
返回一个已完成的
任务
,而不是从
发送邮件
返回的
任务

没有任何内容等待完成
发送邮件

只需等待从方法返回的
任务

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

wait
关键字为您打开
Task.Result

删除
Task.FromResult(…)
。只需在SendMails上直接调用它:
var isSent=await SendMails(…)
@Silvermind我想要用于错误捕获的结果布尔值。如果删除TaskResult,则无法获取返回值。是否有其他方法可以查看返回值?确保调用
SendMails
的方法标记为async,并确保调用标记为async并等待调用的方法。以此类推,一直到调用堆栈。您可以获得异步调用的结果
bool myResult=wait SendMails(/*params*/)另外,请注意SendGrid的邮件系统是一个队列,因此,您正在执行的任务只会在SendGrid的队列中产生一个条目。现在,它们处理队列的速度非常快,但您仍然会不时注意到发送之间有轻微的延迟。在我看来,这种情况正在发生。@JohnathanBarclay:在op的代码中,从
sendMails
返回的任务在调用
Result
时可能完成,也可能不完成。仔细查看这些调用,特别注意
FromResult
调用的返回类型,您应该会发现问题所在。我确实花了一分钟的时间。。。我认为我从未见过将任务传递给
等待任务。FromResult
之前。:)
bool result = await SendMails(formCollection["email"], formCollection["name"], pdfPath, imgPath);