WEB开发网
开发学院WEB开发ASP.NET asp.net2.0中异步调用WebService(异步页) 阅读

asp.net2.0中异步调用WebService(异步页)

 2006-06-21 17:09:03 来源:WEB开发网   
核心提示:由于asp2.0提供了异步页的支持使异步调用WebService的性能有了真正的提升,使用异步页,asp.net2.0中异步调用WebService(异步页),首先要设置Async="true",异步页是在PRerender和PrerenderComplete事件间加入Begin,在*Async完成

由于asp2.0提供了异步页的支持使异步调用WebService的性能有了真正的提升。
使用异步页,首先要设置Async="true",异步页是在PRerender和PrerenderComplete事件间加入Begin,end异步方法实现的,Begin和End方法属于不同的线程。
WS异步页的实现有两种方式:
1、使用等待方法实现异步
通用类,封装了WS
/**//// <summary>
     /// 使用等待方法实现异步
     /// </summary>
     /// <param name="name"></param>
     /// <returns></returns>
     private Account account;
     private string username;
     public Account Account
     {
       get { return account; }
       set { account = value; }
     }
     public string Username
     {
       get { return username; }
       set { username = value; }
     }
     public IAsyncResult BeginAsyncGetAccount(object sender, EventArgs e, AsyncCallback cb, object state)
     {
     
       return vb.BeginGetAccountbyName(username,cb,state);
     }
     public void EndAsyncGetAccount(IAsyncResult ar)
     {
       account = vb.EndGetAccountbyName(ar);
     }

    /**//// <summary>
     /// 使用事件驱动的异步
     /// </summary>
     /// <param name="username"></param>
     public void GetAccountCompleted(Object source, VB.GetAccountbyNameCompletedEventArgs e)
     {
       account = e.Result;
     }
     public void AsGetAccount(string username)
     {
            vb.GetAccountbyNameCompleted += new GetAccountbyNameCompletedEventHandler(GetAccountCompleted);
       vb.GetAccountbyNameAsync(username)
      
     }调用方法
 protected void Page_Load(object sender, EventArgs e)
   {
     this.PreRenderComplete += new EventHandler(Page_PreRenderComplete);
     b.Username = "dinghao";
   
     AddOnPreRenderCompleteAsync(b.BeginAsyncGetAccount, b.EndAsyncGetAccount);
   }
   protected void Page_PreRenderComplete(object sender, EventArgs e)
   {
     //异步调用结束
     VB.Account a = b.Account;
     AccountIf ai = new AccountIf(a);
     ais[0] = ai;
     GridView1.DataSource = ais;
     GridView1.DataBind();
   }由于AddOnPreRenderCompleteAsync的两个委托都是Void类型,所以在通用类中要加入有返回值的属性如:Account供主调方法使用,另外委托中没有异步方法的参数信息,要加入参数的属性如:Username
2、事件驱动的异步(2.0新增)
调用方法:
protected void Page_Load(object sender, EventArgs e)
   {
     this.PreRenderComplete += new EventHandler(Page_PreRenderComplete);
     b.AsGetAccount("dinghao");
  
   }
   protected void Page_PreRenderComplete(object sender, EventArgs e)
   {
     //异步调用结束
     VB.Account a = b.Account;
     AccountIf ai = new AccountIf(a);
     ais[0] = ai;
     GridView1.DataSource = ais;
     GridView1.DataBind();
   }这种调用方式,用的是*Completed事件,在*Async完成时触发,这种调用方式可以
省去Account,Username属性,用起来比较简单

http://bluewater.cnblogs.com/archive/2006/06/20/430758.html

Tags:asp net 异步

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接