4

我正在编写一些实用程序代码来发送异步电子邮件。

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)有没有更好的方法来处理我的任务而不会“适得其反”?

4

1 回答 1

2

您需要从多少个不同的页面发送邮件?

另外,当您尝试发送异步时遇到了什么错误?请编辑您的问题以包含整个异常。

考虑创建一个(异步)页面来发送电子邮件。您可以使用 Server.Transfer 调用该页面,并在完成后将其重定向回您想要的页面。

最后,如果您发送的电子邮件太多以至于在同步发送邮件时会失去性能,那么也许您应该创建一个 Windows 服务来发送实际的电子邮件。您的 ASP.NET 页面会将对此服务的请求(通过 MSMQ 或 WCF)排队,以让该服务发送电子邮件。

于 2009-07-02T16:07:23.377 回答