繁体   English   中英

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

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

我有一个名为mainForm的类,它是程序的主窗口。 我在此类中创建一个TextBox(此TextBox Logs程序)对象,我想向其写入程序状态。 我可以很容易地从mainForm和其他对象(通过将TextBox对象传递给它)来做到这一点,但是当我想从另一个线程来做到这一点时,这很复杂。 但是,我正在通过它在mainForm(使用委托)中运行定义的代码的线程向TextBox写入。

我的问题是,如何从在另一个类中运行的线程在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?
   }
}

您可以使用Invoke / BeginInvoke

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

这使辅助线程可以安全地将GUI更改转发到GUI线程,这是应该应用它们的唯一方法。

使用定义的委托的另一种方法-顺便说一下,这里Xt可以重用于其他方法,只要签名是相同的。 也可以传递参数-(然后在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