我正在编写一些实用程序代码来异步发送电子邮件。
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
A final point to keep in mind as you build asynchronous pages is that you should not launch asynchronous operations that borrow from the same thread pool that ASP.NET uses. For example, calling ThreadPool.QueueUserWorkItem at a page's asynchronous point is counterproductive because that method draws from the thread pool, resulting in a net gain of zero threads for processing requests. By contrast, calling asynchronous methods built into the Framework, methods such as HttpWebRequest.BeginGetResponse and SqlCommand.BeginExecuteReader, is generally considered to be safe because those methods tend to use completion ports to implement asynchronous behavior.
问题:
1) 如何在我的 C# 代码中将页面更新为异步?
2) 如果我不能,那么强制我的所有页面都为 Async=true 的缺点是什么?
3) 有没有更好的方法来安排我的任务而不“适得其反”?
最佳答案
您需要从多少个不同的页面发送邮件?
此外,当您尝试发送异步时遇到了什么错误?请编辑您的问题以包含整个异常。
考虑创建一个(异步)页面来发送电子邮件。您可以使用 Server.Transfer 调用该页面,并在完成后将其重定向回您想要的页面。
最后,如果您发送的电子邮件太多以至于在同步发送邮件时性能下降,那么您或许应该创建一个 Windows 服务来发送实际的电子邮件。您的 ASP.NET 页面会将对此服务的请求(通过 MSMQ 或 WCF)排队,以让该服务发送电子邮件。
关于c# - 如何动态设置异步页面指令以便异步方法工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1074976/