C # controls created in one thread cannot be filtered to a control in another thread

I start a thread and this thread grabs information and creates labels and displays 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 I had a previous app with a panel and I used to add controls to it using streams without any problem, but this one won't let me do it.

+3


source to share


3 answers


You cannot update the 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);
            }
        }

      

+8


source


You need to use BeginInvoke to safely access the UI thread 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);
    }));

      

+5


source


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

use Invoke to safely access the UI thread 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);
    });

      

+3


source







All Articles