我正在编写一些实用程序代码来发送异步电子邮件。
var mailClient = new SmtpClient(smtpHost);
mailClient.SendCompleted += new SendCompletedEventHandler(mailClient_SendCompleted);
using (var mailMessage = new MailMessage())
{
if (!((System.Web.UI.Page)HttpContext.Current.CurrentHandler).IsAsync)
{
// set to Async????
}
mailClient.SendAsync(mailMessage, new { EmailID });
}
但是我收到错误,因为我的页面在页面指令中没有 Async="true" 。
这是您得到的标准错误:
"Asynchronous operations are not allowed in this context. Page starting an asynchronous operation has to have the Async attribute set to true and an asynchronous operation can only be started on a page prior to PreRenderComplete event."
我读到这个:(最后一段)
http://msdn.microsoft.com/en-us/magazine/cc163725.aspx
在构建异步页面时要记住的最后一点是,不应启动从 ASP.NET 使用的同一线程池借用的异步操作。例如,在页面的异步点调用 ThreadPool.QueueUserWorkItem 会适得其反,因为该方法从线程池中提取,导致用于处理请求的净增益为零。相比之下,调用框架中内置的异步方法,如 HttpWebRequest.BeginGetResponse 和 SqlCommand.BeginExecuteReader 等方法,通常被认为是安全的,因为这些方法倾向于使用完成端口来实现异步行为。
问题:
1) 如何在我的 c# 代码中将页面更新为异步?
2) 如果我不能强制我的所有页面都为 Async=true 有什么缺点?
3)有没有更好的方法来处理我的任务而不会“适得其反”?