【问题标题】:How to update a Label on the UI thread/class within a selenium thread/class如何在 selenium 线程/类中更新 UI 线程/类上的标签
【发布时间】:2016-08-11 20:26:44
【问题描述】:

所以我对如何从 selenium 线程更新 UI 线程上的标签有疑问。如您所见,selenium 线程调用“selenium”方法,该方法使用其他类的静态方法(Login.UserLogin, Run.StartDriver)。

我似乎不知道如何从登录或运行类更改此类中的标签。抱歉,如果编码是业余爱好者,我刚开始学习 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();
     }

}

【问题讨论】:

    标签: c# multithreading user-interface selenium


    【解决方案1】:
    1. 在 Login/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);
              }
      
          }
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-28
      • 1970-01-01
      • 2015-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多