2011-10-25 35 views
0

這是我的服務,檢查用戶名和密碼啓用Silverlight的WCF服務重新調諧價值

[OperationContract] 

    public bool LoginCheck(string username, string password) 
    { 
     RoadTransDataContext db = new RoadTransDataContext(); 

     var _Pass = (from d in db.users where d.username == username select d.password).SingleOrDefault(); 

     if (_Pass == password) 
     { 
      return true; 
     } 
     else 
     { 
      return false; 
     } 
    } 

這是子窗口

private void LoginCheckCompleted(object sender, ServiceReference.LoginCheckCompletedEventArgs e) 
    { 
     _Log = e.Result; 
    } 

    private void OKButton_Click(object sender, RoutedEventArgs e) 
    { 
     ServiceReference.ServiceClient webservice = new ServiceReference.ServiceClient(); 

     webservice.LoginCheckCompleted += new EventHandler<ServiceReference.LoginCheckCompletedEventArgs>(LoginCheckCompleted); 
     webservice.LoginCheckAsync(txtUserName.Text, txtPassword.Password); 

     if (_Log == true) 
     { 
      this.DialogResult = true; 
      this.Close(); 
     } 
    } 

問題是,當OKButton_Click方法完成LoginCheckCompleted方法調用。所以如果它輸入正確的用戶名,傳遞並按下按鈕它什麼都不做,如果我再次單擊一次窗口關閉

+0

順便說一句,服務方法的代碼大小可以減少:'return db.users.Where(d => d.username == username && d.password ==密碼).Any();' – vorrtex

回答

2

Silverlight使用調用Web服務的異步模型,它需要一些時間來等待,直到返回響應。在你的例子中,分配_Log = e.Result;將被調用,讓我們假設,1-2秒後,而檢查if (_Log == true)將被稱爲immideately,當然之前的任務。

這就是爲什麼你應該把所有必要的代碼放在回調中,並在異步調用後刪除所有代碼。我已經爲您修復了這個問題:

private void LoginCheckCompleted(object sender, ServiceReference.LoginCheckCompletedEventArgs e) 
{ 
    _Log = e.Result; 

    if (_Log == true) 
    { 
     this.DialogResult = true; 
     this.Close(); 
    } 
} 

private void OKButton_Click(object sender, RoutedEventArgs e) 
{ 
    ServiceReference.ServiceClient webservice = new ServiceReference.ServiceClient(); 

    webservice.LoginCheckCompleted += new EventHandler<ServiceReference.LoginCheckCompletedEventArgs>(LoginCheckCompleted); 
    webservice.LoginCheckAsync(txtUserName.Text, txtPassword.Password); 
}