我發送一個簡單的電子郵件操作: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