我发送一个简单的电子邮件操作:SmtpClient.SendAsync挡住了我的ASP.NET MVC请求
[HttpPost, ActionName("Index")]
public ActionResult IndexPost(ContactForm contactForm)
{
if (ModelState.IsValid)
{
new EmailService().SendAsync(contactForm.Email, contactForm.Name, contactForm.Subject, contactForm.Body, true);
return RedirectToAction(MVC.Contact.Success());
}
return View(contactForm);
}
和电子邮件服务:
public void SendAsync(string fromEmail, string fromName, string subject, string body, bool isBodyHtml)
{
MailMessage mailMessage....
....
SmtpClient client = new SmtpClient(settingRepository.SmtpAddress, settingRepository.SmtpPort);
client.EnableSsl = settingRepository.SmtpSsl;
client.Credentials = new NetworkCredential(settingRepository.SmtpUserName, settingRepository.SmtpPassword);
client.SendCompleted += client_SendCompleted;
client.SendAsync(mailMessage, Tuple.Create(client, mailMessage));
}
private void client_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
Tuple<SmtpClient, MailMessage> data = (Tuple<SmtpClient, MailMessage>)e.UserState;
data.Item1.Dispose();
data.Item2.Dispose();
if (e.Error != null)
{
}
}
当我发电子邮件,我使用Async方法,然后我的方法SendAsync立即返回,然后调用RedirectToAction。但是,在client_SendCompleted完成之前,ASP.NET不会发送响应(在本例中为重定向)。
这里就是我想明白了:
在观看在Visual Studio调试器的执行过程中,SendAsync立即(和RedirectToAction叫)返回,但什么也没有发生在浏览器中,直到发送电子邮件?
如果我在client_SendCompleted中放置了一个断点,客户端会一直在加载....直到我在调试器中点击F5。
如果我使用Task.Factory.StartNew(()=> SendEmail(),TaskCreationOptions.LongRunning)我会有同样的问题? –
[我应该永远不会调用HostingEnvironment.UnregisterObject?](http://stackoverflow.com/questions/16096378/should-i-never-call-hostingenvironment-unregisterobject) – horgh