由於silverlight在調用RIA時採用的異步調用模式,即向服務器端發出了調用請求後繼續執行下面的操作,而無視服務器端返回的結果。爲了能夠讓返回結果影響下面的操作需要進行同步處理。示例
private void Button_Click(object sender, RoutedEventArgs e)
{
InvokeOperation op = service.Login(this.txUserCode.Text, this.txPassword.Password, LoginUser, null);
op.Completed+=new EventHandler(op_Completed);
}
private void LoginUser(InvokeOperation op)
{
if(op.HasError)
{
MessageBox.Show(op.Error.Message);
}
else
{
curUser = op.Value as SYS_USER;
}
}
void op_Completed(object sender, EventArgs e)
{
if (curUser == null || curUser.USERID == null)
{
MessageBox.Show("用戶密碼錯誤!");
}
}
如上代碼
InvokeOperation op = service.Login(this.txUserCode.Text, this.txPassword.Password, LoginUser, null);
實際是執行了WCF中的一個方法,並在執行後使用LoginUser這個回調函數來處理數據,添加了op_Completed事件確保服務器端方法執行完畢後再執行新的操作。
要在服務器端定義異步方法需要使用[Invoke]標籤。例如
[Invoke]
public SYS_USER Login(string userName, string password)
{
//操作
}