简体   繁体   中英

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. I create a TextBox(this TextBox Logs program) object in this class and i want to write program status to it. 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. However, i am writing to TextBox by the thread that it runs the defined code in mainForm(using delegate).

My question is, How to write in the TextBox from thread that runs in another class?

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 :

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.

Another way using defined delegate - incidently Xt here can be reused for other methods as long as the signature is the same. 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.

private void run() 
    { 
          XteChangeText();
    } 

    private delegate void Xt();

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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