2016-08-11 40 views
1

所以我有一個問題,如何更新硒線程的UI線程上的標籤。正如你看到硒線程調用使用其他類的靜態方法(Login.UserLogin,Run.StartDriver)的「selenium」方法。如何更新硒線程/類內的UI線程/類的標籤

我似乎無法弄清楚如何從登錄或運行類更改此類中的標籤。對不起,如果編碼是業餘的,我剛開始學習C#。

public class Form1{ 

private void startThread() 
    { 
     if (seleniumThread == null) 
     { 
      stopThread = false; 
      seleniumThread = new Thread(() => selenium(userName, passWord, 
      cyclesWanted)); 

      seleniumThread.Start(); 
     } 
    } 

private void selenium(string user, string pass, int cycles) 
    { 

     driver = new FirefoxDriver(); 

     Login.UserLogin(driver, user, pass); 

     Run.StartDriver(driver, cycles); 

     if (stopThread) 
     { 
      driver.Quit(); 
      return; 
     }   
    } 

private void button1_Click(object sender, EventArgs e) 
    { 
    startThread(); 
    } 

}

回答

0
  1. 在登錄/ Run類添加靜態事件
  2. 在Form類註冊到事件
  3. 當活動將由this.beginInvoke提高更新標籤()函數(因爲它不是UI線程)。

    public class Login 
        { 
    
         public static event Action<string> TextChange; 
    
    
         private static void OnTextChange(string newText) 
         { 
          if (TextChange != null) 
           TextChange(newText); 
         } 
    
         public static void UserLogin(string driver, string userName,string password) 
         { 
          OnTextChange(userName); 
         } 
    
        } 
    
    
        public class Form1 
        { 
    
         private void registerLoginEvent() 
         { 
          Login.TextChange += Login_TextChange; 
         } 
    
         private void Login_TextChange(string newText) 
         { 
          this.BeginInvoke(()=>label.text = newText); 
         } 
    
        }