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