在非异步方法C#中调用async void方法

时间:2014-04-10 17:20:19

标签: c# asynchronous

我在非异步方法中调用async void函数时遇到问题。我收到内部服务器错误。我已经搜索了这个问题并找到了TASK而不是TASK的答案。我的情况不是任务所以我应该调用task.RunSynchronously()。这将等待我的异步方法完成,然后继续下一个点。但是当我调试它会导致服务器错误。

private async void MyMthodAsync(int userId, string email)
{
    var emailTemplate = await EmailTemplateLoader.Load(EmailTemplateFile);
    var Message = new MailMessage(emailTemplate.`enter code here`From, email)
    {
        Subject = emailTemplate.Subject,
        Body = emailTemplate.Body,
        IsBodyHtml = true,
        BodyEncoding = Encoding.UTF8
    };
    await EmailSender.Send(Message);
}

我在无异步方法

中调用异步方法
public HttpResponseMessage ChangePassword([FromBody]ChangePasswordModel model)
{
    Task sendEmail = new Task(()=>MyMthodAsync(model.userId, model.email));
    sendEmail.RunSynchronously();

    return TheResponse.CreateSuccessResponse(Constants.PasswordHasBeenSuccessfullyChanged);
}

我的回复是内部服务器错误。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

避免使用async void,除非它是一个事件处理程序。将返回类型更改为Task

private async Task SendChangePasswordEmailAsync(int userId, string email)
{
    var emailTemplate = await EmailTemplateLoader.Load(EmailTemplateFile);
    var Message = new MailMessage(emailTemplate.From, email)
    {
        Subject = emailTemplate.Subject,
        Body = emailTemplate.Body,
        IsBodyHtml = true,
        BodyEncoding = Encoding.UTF8
    };

    await EmailSender.Send(Message);
}

然后更改方法以使用async - await

public async Task<HttpResponseMessage> ChangePassword(
    [FromBody]ChangePasswordModel model
)
{
    await SendChangePasswordEmailAsync(model.userId, model.email);

    return TheResponse
        .CreateSuccessResponse(Constants.PasswordHasBeenSuccessfullyChanged);
}