Search code examples
c#thread-safetyinvokeinvokerequired

Invoke self to bypass different threads? C#


I have been looking around for about 3 hours and can not get this invoke to work. I need the invoke because whats calling it is in a different thread and says its unstable.

Here's what I'm calling (I call it like this textBox1_TextChanged(null, null);):

 private void textBox1_TextChanged(object sender, EventArgs e)
 {
     if(this.InvokeRequired)
     {
        this.Invoke(this?WHAT GOES HERE, null); // I know it should be a delegate or something but I can't change this to that
     }
     else
     {
        string temp = ""; 
        temp += TextToAdd;
        textBox1.Text = "s";
     }
}

Solution

  • You can use BeginInvoke to update the UI from other Thread.

    if (this.InvokeRequired)
    {
      var action = new Action(() => textBox1.Text = "s");
      this.BeginInvoke(action);
    }