简体   繁体   中英

ASP.NET Web API Async Tasks, sending Mails

my application has massive performance problems. I found that the problem comes from the sending of emails. How can i fix this problem that the method RegisterUser returns, while the sending of the email is still in process? I already tried this with starting a thread to run the SendEmailConfirm Method, but that gave me an ObjectDisposedException in SendEmailConfirm

public async Task<IdentityResult> RegisterUser(AccountViewModels.RegisterViewModel userModel)
{
    var result = await _userManager.CreateAsync(user, userModel.Password);
    this.SendEmailConfirm(userModel.Email);

    return result;
}

public async void SendEmailConfirm(string mail)
{

    string subject = "Please confirm your Email for Chronicus";
    string body = "Hello"
    string email = user.Email;

    _messageService.SendMail(mail, subject, body);

}

public void SendMail(string receiver, string subject, string body)
    {
        this._msg = new MailMessage(UserName, receiver);
        this._msg.From = new MailAddress(UserName, Name);
        this._msg.Subject = subject;
        this._msg.Body = body;
        this._msg.IsBodyHtml = true;
        this._smtpClient.Send(_msg);
    }

EDIT: Added SendMail method to the question

You need to use the SendMailAsync method of the SmtpClient class.

Also, you should return Task for async method that return no value.

Here is how your code would look like:

public async Task<IdentityResult> RegisterUser(AccountViewModels.RegisterViewModel userModel)
{
    var result = await _userManager.CreateAsync(user, userModel.Password);
    await this.SendEmailConfirm(userModel.Email);

    return result;
}

public Task SendEmailConfirm(string mail)
{
    string subject = "Please confirm your Email for Chronicus";
    string body = "Hello"
    string email = user.Email;

    return _messageService.SendMail(mail, subject, body);
}

And here is how SendMail would look like:

public Task SendMail(string receiver, string subject, string body)
{
    this._msg = new MailMessage(UserName, receiver);
    this._msg.From = new MailAddress(UserName, Name);
    this._msg.Subject = subject;
    this._msg.Body = body;
    this._msg.IsBodyHtml = true;

    return this._smtpClient.SendMailAsync(_msg);
}

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