由於asp2.0提供了非同步頁的支援使非同步呼叫WebService的效能有了真正的提升。
使用非同步頁,首先要設定Async="true",非同步頁是在Prerender和PrerenderComplete事件間加入Begin,end非同步方法實現的,Begin和End方法屬於不同的執行緒。
WS異步頁的實作有兩種方式:
1.使用等待方法實現異步通用類,封裝了WS
/**////
/// 使用等待方法實現非同步
///
///
///
private Account account;
private string username;
public Account Account
{
get { return account; }
設置 { account = 值; }
}
public string Username
{
get { return username; }
set { username = 值; }
}
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);
}
/**////
/// 使用事件驅動的非同步
///
///
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