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

- 中国WEB开发者网络 (http://www.webasp.net)
-- 技术教程 (http://www.webasp.net/article/)
--- asp.net2.0中异步调用WebService(异步页) (http://www.webasp.net/article/28/27925.htm)
-- 作者:未知
-- 发布日期: 2006-10-30
 

由于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

转自:动态网站制作指南 | www.knowsky.com

webasp.net