2010-01-28 18 views
1

我想創建一個登錄表單。我遇到的問題是登錄過程耗時過長,並且鎖定了我的GUI。我已經閱讀了背景工作者,但我仍然不確定如何讓我的程序等待登錄過程,但不凍結我的GUI。這裏是我的代碼,以幫助更多地解釋它。C#關於如何防止GUI凍結的問題,但仍然處於阻塞狀態

Login.cs

public partial class Login : Form 
{ 
    public delegate bool Authenicate(string account, string password,string type); 
    public Authenicate authenicate; 
    public Login() 
    { 
     InitializeComponent(); 
    } 

    private void btnLogin_Click(object sender, EventArgs e) 
    { 
     if (txtAccount.Text == string.Empty) 
     { 
      MessageBox.Show("Must include account number", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); 
      return; 
     } 
     if (txtPassword.Text == string.Empty) 
     { 
      MessageBox.Show("Must include password", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); 
      return; 
     } 
     if (!authenicate(txtAccount.Text, txtPassword.Text,cmbType.Items[cmbType.SelectedIndex].ToString())) 
     { 
      return; 
     } 
     this.DialogResult = DialogResult.OK; 
    } 

    private void Login_Load(object sender, EventArgs e) 
    { 
     cmbType.SelectedIndex = 0; 
    } 

MainForm.cs

public partial class MainForm: Form 
{ 
    Ex.Service myService=new Ex.Service(); 

    public MainForm() 
    { 
     InitializeComponent(); 
    } 
    public bool Authenicate(string account, string password,string type) 
    { 
     try 
     { 
      //Login takes too long and locks up GUI 
      //Maybe try background worker, but how to wait until 
      //login is complete? 
      myService.Login(account,password,type); 
      return myService.IsLogin(); 
     } 
     catch(Exception exception) 
     { 
      MessageBox.Show(exception.message); 
     } 
     return false; 
    } 

    private void MainForm_FormClosing(object sender, FormClosingEventArgs e) 
    { 
     myService.Logout(); //Logout from service 
     myService = null; 
    } 
} 

謝謝您的時間。

回答

1

的一般步驟是:

  1. 背景工人添加到您的登錄對話框
  2. 創建調用您驗證委託的背景工人的DoWork事件的事件處理程序。
  3. 在btnLogin_Click中禁用登錄對話框,以便用戶在後勤員工正在運行時不能再次單擊登錄。
  4. 在btlLogin_Click中調用BackGround工作人員的RunWorkAsync方法來啓動工作人員運行。
  5. 爲Background Worker的RunWorkerCompleted事件創建事件處理程序。在這種情況下,啓用LoginForm並在登錄結果成功時關閉對話框或顯示en錯誤消息。
+0

謝謝你的明確和有益的答案。 – Dylan 2010-01-28 05:33:19

0

我會說在登錄表單中創建一個事件,並在主窗體中進行訂閱。在登錄表單中,如果時間太長,您可以使用該線程執行登錄任務。一旦登錄成功或失敗,您可以使用此事件通知主窗體並將事件參數中的附加信息發送到主窗體。

收到此事件後,主窗體可以根據您設定的條件進行。

0

禁用相關的UI元素(按鈕,文本框等),然後啓動後臺工作線程。完成後,根據需要更新UI。

與UI通信可能採取LoginSucceededLoginFailed事件的形式,或類似。

相關問題