ASP.NET Web API 异步任务,发送邮件
本文关键字:任务 NET Web API 异步 ASP | 更新日期: 2023-09-27 18:32:21
我的应用程序存在大量性能问题。我发现问题来自发送电子邮件。如何解决该方法RegisterUser
返回的问题,而电子邮件的发送仍在进行中?我已经尝试过启动一个线程来运行 SendEmailConfirm
方法,但这给了我一个ObjectDisposedException
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);
}
编辑:在问题中添加了发送邮件方法
您需要使用 SmtpClient
类的 SendMailAsync
方法。
此外,对于不返回任何值的异步方法,应返回Task
。
以下是您的代码的外观:
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);
}
以下是SendMail
的样子:
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);
}