ASP.NET 异步页面

1、同步和异步的区别

当未使用异步页时,一个线程只能为同一个页面的请求服务. 即使页面请求过程中处理其它的I/O等操作时,此线程也一直处于等待状态. 当此页面使用完此线程时,才将它放回到线程池. 线程数量是有限的! 所以当不使用线程时及时放回线池可以使系统性能大大提高!
当使用了异步页功能时,如右图中,开始Thread1是为页面服务的,但当页面处理其它的事情(比如I/O或调用其它WebService) 时,Thread1被放回线程池, 此时Thread1可以为其它页面请求服务了. 当此页面执行完自己的操作回来后, Thread2接着为页面请求服务,并不是使用的原来的线程Thread1. 这样网站的伸缩性会更好.

image

2、使用示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
public  partial  class  _Default : System.Web.UI.Page
{
     const  string  RSSFEED = "http://weblogs.asp.net/scottgu/rss.aspx" ;
     private  WebRequest req;
     public  string  rssResult;
     public  int  tick;
     protected  void  Page_Load( object  sender, EventArgs e)
     {
         int  started = System.Environment.TickCount;
         AddOnPreRenderCompleteAsync(
             new  BeginEventHandler(BeginTask),
             new  EndEventHandler(EndTask));
 
         tick = System.Environment.TickCount - started;
 
         //PageAsyncTask task = new PageAsyncTask(
         //    new BeginEventHandler(BeginTask),
         //    new EndEventHandler(EndTask),
         //    new EndEventHandler(TimeOut),
         //    null);
 
 
         //RegisterAsyncTask(task);
 
     }
 
     IAsyncResult BeginTask( object  sender, EventArgs e, AsyncCallback cb, object  state)
     {
         Trace.Warn( "Begin asyc: Thread="  + Thread.CurrentThread.ManagedThreadId.ToString());
 
         req = WebRequest.Create(RSSFEED);
         return  req.BeginGetResponse(cb, state);
     }
 
     void  EndTask(IAsyncResult ar)
     {
 
         using  (WebResponse response = req.EndGetResponse(ar))
         {
             StreamReader reader;
             using  (reader = new  StreamReader(response.GetResponseStream()))
             {
                 rssResult = reader.ReadToEnd();
             }
 
         }
 
         Trace.Warn( "End async: Thread="  + Thread.CurrentThread.ManagedThreadId.ToString());
     }
 
     void  TimeOut(IAsyncResult ar)
     {
         Response.Write( "Time Out" );
         Response.End();
     }
     }

前台页面

image

image

本文转自敏捷的水博客园博客,原文链接http://www.cnblogs.com/cnblogsfans/archive/2009/11/05/1596619.html如需转载请自行联系原作者


王德水

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值