C# How to update GUI from another thread?

Assuming I have a form named Form1:

  1. public partial class Form1 : Form
  2. {
  3. public Form1()
  4. {
  5. InitializeComponent();
  6. }
  7. private void UpdateText(object text)
  8. {
  9. button1.Text = text.ToString();
  10. }
  11. private void Form1_Load(object sender, EventArgs e)
  12. {
  13. Thread th = new Thread(new ParameterizedThreadStart(UpdateText));
  14. th.IsBackground = true;
  15. th.Start("hello world");
  16. }
  17. }

Run the form, i got error "InvalidOperationException was unhandled"

Cross-thread operation not valid: Control 'button1' accessed from a thread other than the thread it was created on.

I fix the above error using the following lines:
  1. private delegate void UpdateTextDel(object text);
  2. private void UpdateText(object text)
  3. {
  4. if (button1.InvokeRequired)
  5. button1.Invoke(new UpdateTextDel(UpdateText), text);
  6. else
  7. button1.Text = text.ToString();
  8. }

Comments