简体   繁体   中英

call async void method within non-async method C#

I am having problem with calling async void function in non async method. I get internal server error. I have googled this issue and got found some answers for TASK and not TASK. my case is not task so i should call task.RunSynchronously(). which will wait to my async method to completed and then continue to the next point. But when i am debugging it brings server error.

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);
}

I am calling above async method in none async method

public HttpResponseMessage ChangePassword([FromBody]ChangePasswordModel model)
{
    Task sendEmail = new Task(()=>MyMthodAsync(model.userId, model.email));
    sendEmail.RunSynchronously();

    return TheResponse.CreateSuccessResponse(Constants.PasswordHasBeenSuccessfullyChanged);
}

I get my response as internal server error.

What am I doing wrong?

Avoid async void unless it is an event handler. Change the return type to 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);
}

Then change the method to use async - await .

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

    return TheResponse
        .CreateSuccessResponse(Constants.PasswordHasBeenSuccessfullyChanged);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM