真正的解决方案:异步请求处理
调整配置设置是一种改善问题的方法,而在实际设计 Web 应用程序时通过某种方式彻底解决问题则是另一回事。等待阻塞的调用完成的线程永远也不会有更好的调整余地,因此,解决的办法是完全避免阻塞问题。异步处理请求就是一个适当的解决方案。这表现在两个方面:进行异步 Web 服务调用,以及在 ASP.NET Web 应用程序中异步处理请求。
异步 Web 服务调用
在以前的专栏中,我写了有关异步调用 Web 服务的问题。能够使线程不用等待 Web 服务调用完成是创建释放线程以便处理更多请求的异步页面处理模型的关键部分。此外,异步调用 Web 服务也比较简单。
请考虑以下 ASPX 页面的 Visual Basic.NET 代码:
| ' 错用同步 Web 服务调用所造成的性能极差的 ' 页面! Public Class SyncPage Inherits System.Web.UI.Page Protected WithEvents Label1 As System.Web.UI.WebControls.Label Protected WithEvents Label2 As System.Web.UI.WebControls.Label Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load '调用 Web 服务 Dim proxy As New localhost.Service1 Label1.Text = proxy.Method1(500) Label2.Text = proxy.Method1(200) End Sub End Class |
| Public Class AsyncPage Inherits System.Web.UI.Page Protected WithEvents Label1 As System.Web.UI.WebControls.Label Protected WithEvents Label2 As System.Web.UI.WebControls.Label Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load '调用 Web 服务 Dim proxy As New localhost.Service1 Dim res As IAsyncResult = proxy.BeginMethod1(500, Nothing, Nothing) Dim res2 As IAsyncResult = proxy.BeginMethod1(200, Nothing, Nothing) Label1.Text = proxy.EndMethod1(res) Label2.Text = proxy.EndMethod1(res2) End Sub End Class |
http://dev.xuezhishi.net/website/NET/2007-10-17/20782.html