【问题标题】:RichTextBox is not updating in Cross thread operationRichTextBox 在跨线程操作中未更新
【发布时间】:2012-12-26 12:10:56
【问题描述】:

这是我的示例代码:

//------this is just GUI Form which is having RichTextBox (Access declared as Public)
//

public partial class Form1 : Form
{
   public void function1()
   {
      ThreadStart t= function2;
      Thread tStart= new Thread(t);
      tStart.Start();
   }

   public void function2()
   {
   //Calling function3 which is in another class
   }
}


//------this is just Class, not GUI Form
class secondClass: Form1
{

   public void function3()
   {
      Form1 f =new Form1();
      //Updating the RichTextBox(which is created in Form1 GUI with Public access)
      f.richTextBox1.AppendText("sample text");
   }

}

我尝试调用richTextBox1 控件,我的代码运行时没有错误,但richtextbox 没有得到更新。

我必须怎么做才能从另一个类函数中频繁更新我在richTextBox 中的状态?

【问题讨论】:

    标签: c# multithreading


    【解决方案1】:

    你的问题在这里:

    public void function3()
    {
    Form1 f =new Form1();
    //Updating the RichTextBox(which is created in Form1 GUI with Public access)
    f.richTextBox1.AppendText("sample text");
    }
    

    您创建表单的另一个实例并对 richTextBox 进行更改 - 不是初始实例。

    要完成这项工作,您应该使用 Invoke 方法在其代码隐藏类中设置 UI 控件的值,如 here 所示。其他类的函数应该为任何输入和输出值使用参数。

    【讨论】:

      【解决方案2】:

      只需将您的 RichTextBox 从 Form1 传递给 function3

          //function inside form1
          public void function2() {
              function3(this.richTextBox1);
          }
      

      然后使用调用从另一个线程/类更新richTextBox

          //function in another thread
          public void function3(RichTextBox r)
          {
              r.InvokeIfRequired((value) => r.AppendText(value), "asd");
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-07
        • 1970-01-01
        • 2015-12-13
        • 2011-07-11
        • 1970-01-01
        相关资源
        最近更新 更多