【发布时间】:2009-07-02 15:12:36
【问题描述】:
我正在编写一些实用程序代码来异步发送电子邮件。
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) 有没有更好的方法来处理我的任务而不会“适得其反”?
【问题讨论】:
标签: c# asp.net asynchronous page-directives