c# – 如何动态设置异步页面指令,以便异步方法起作用

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

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 });
}

但是我收到错误,因为我的Pages在页面指令中没有Async =“true”.

这是你得到的标准错误:

06001

我读到了这个:(最后一段)

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#代码中将页面更新为Async?

2)如果我不能强迫我的所有页面都是Async = true是什么?

3)有没有更好的方法来完成我的任务而不会“适得其反”?

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

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

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

最后,如果您发送的电子邮件太多而在同步发送邮件时会丢失性能,那么您可能应该创建一个Windows服务来发送实际的电子邮件.您的ASP.NET页面会将请求排入此服务(通过MSMQ或WCF)以使服务发送电子邮件.

点赞