简体   繁体   English

从另一个线程c#访问主要形式的文本框组件

[英]access to textbox component in main form from another thread c#

I have the class called mainForm that it is main window of my program. 我有一个名为mainForm的类,它是程序的主窗口。 I create a TextBox(this TextBox Logs program) object in this class and i want to write program status to it. 我在此类中创建一个TextBox(此TextBox Logs程序)对象,我想向其写入程序状态。 I do this from mainForm and other object(by passing TextBox object to it) easily, But when i want to do that from another thread, it's complicated. 我可以很容易地从mainForm和其他对象(通过将TextBox对象传递给它)来做到这一点,但是当我想从另一个线程来做到这一点时,这很复杂。 However, i am writing to TextBox by the thread that it runs the defined code in mainForm(using delegate). 但是,我正在通过它在mainForm(使用委托)中运行定义的代码的线程向TextBox写入。

My question is, How to write in the TextBox from thread that runs in another class? 我的问题是,如何从在另一个类中运行的线程在TextBox中编写代码?

public partial class mainForm : Form
{
   TextBox log = new TextBox();
   .
   .
   .
   OtherClass o = new OtherClass(log);
}
class OtherClass
{
   private TextBox log;
   public otherClass(TextBox aLog)
   {
      log = aLog;
      Thread thread = new Thrad(new ThreadStart(this.run));
      thread.Start();
   }
   private void run()
   {
      log.Text = "Message";// I Can't Do This. Can I Use Delegate Here? How?
   }
}

You can use Invoke / BeginInvoke : 您可以使用Invoke / BeginInvoke

log.BeginInvoke(
    (Action)(() =>
    {
       log.Text = "Message";
    }));

This allows the secondary thread to safely forward GUI changes to the GUI thread which is the only one that should apply them. 这使辅助线程可以安全地将GUI更改转发到GUI线程,这是应该应用它们的唯一方法。

Another way using defined delegate - incidently Xt here can be reused for other methods as long as the signature is the same. 使用定义的委托的另一种方法-顺便说一下,这里Xt可以重用于其他方法,只要签名是相同的。 Parameters can also be passed - (would then have parameters in the Xt delegate and Invoke of it would pass a coma separated list for each. 也可以传递参数-(然后在Xt委托中具有参数,对其的调用将为每个传递逗号分隔的列表。

private void run() 
    { 
          XteChangeText();
    } 

    private delegate void Xt();

    private void XteChangeText()
    {
        if (log.InvokeRequired)
        {
        Invoke(new Xt(XteChangeText));
        }
        else
        {
        log.Text="Message";
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM