0

Can someone tell me why the below code is not working?

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        Thread t = new Thread(rtb2);
        t.Start();
    }

    private void rtb2()
    {
        try
        {
            richTextBox1.Text = "1";                
        }
        catch(InvalidOperationException ex)
        {
            MessageBox.Show("HI");
        }            
    }
}
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
CodeLive
  • 45
  • 4
  • 1
    Please define "not working", but I'd bet it was because you're not using `Control.Invoke` to update the UI. – ChrisF Jan 07 '12 at 00:51
  • 1
    JaredParand ChristF are both right ... but you really should have been clearer about "Not working" ;) – paulsm4 Jan 07 '12 at 00:55
  • FWIW, for short lived threads, use ThreadPool.QueueUserWorkItem over spawning a new thread. http://stackoverflow.com/questions/230003/thread-vs-threadpool – Phil Price Jan 07 '12 at 00:56
  • Since you knew that an exception was being thrown you could have figured out the problem from the exception itself: MessageBox.Show("HI "+ex.ToString()); – Mike W Jan 07 '12 at 01:06

1 Answers1

6

The problem is your attempting to modify a Winforms UI element from a background thread. This is specifically not allowed by the WinForms model. UI elements can only be modified from the main thread. You need to use Control.Invoke in order to get the context back onto the appropriate thread.

private void rtb2() {
  Action action = delegate {
    richTextBox1.Text = "1";
  };

  try {
    this.Invoke(action);
  } catch(InvalidOperationException ex) {
     MessageBox.Show("HI");
  }
}
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454