8

I am running a thread and that thread grabs information and create labels and display it, here is my code

    private void RUN()
    {
        Label l = new Label();
        l.Location = new Point(12, 10);
        l.Text = "Some Text";
        this.Controls.Add(l);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Thread t = new Thread(new ThreadStart(RUN));
        t.Start();
    }

The funny thing is that i had a previous application that has a panel and i used to add controls to it using threads without any issue, but this one won't let me do it.

BOSS
  • 1,828
  • 11
  • 34
  • 60

3 Answers3

12

You cannot update UI thread from another thread:

 private void RUN()
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke((MethodInvoker)delegate()
                {
                    Label l = new Label(); l.Location = new Point(12, 10);
                    l.Text = "Some Text";
                    this.Controls.Add(l);
                });
            }
            else
            {
                Label l = new Label();
                l.Location = new Point(12, 10);
                l.Text = "Some Text";
                this.Controls.Add(l);
            }
        }
Igoy
  • 2,942
  • 22
  • 23
6

You need to use BeginInvoke to access the UI thread safely from another thread:

    Label l = new Label();
    l.Location = new Point(12, 10);
    l.Text = "Some Text";
    this.BeginInvoke((Action)(() =>
    {
        //perform on the UI thread
        this.Controls.Add(l);
    }));
Nathanial Woolls
  • 5,231
  • 24
  • 32
  • Couldn't use it Error 1: Using the generic type 'System.Action' requires 1 type arguments – BOSS Feb 07 '13 at 12:25
3

Your are trying to add control to a parent control from a different thread , controls can be added to parent control only from the thread parent control was created!

use Invoke to access the UI thread safely from another thread:

    Label l = new Label();
    l.Location = new Point(12, 10);
    l.Text = "Some Text";
    this.Invoke((MethodInvoker)delegate
    {
        //perform on the UI thread
        this.Controls.Add(l);
    });
Community
  • 1
  • 1
Parimal Raj
  • 20,189
  • 9
  • 73
  • 110