8

私はスレッドを実行していて、そのスレッドは情報を取得してラベルを作成し、それを表示します。これが私のコードです

    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();
    }

面白いことに、以前はパネルを備えたアプリケーションがあり、スレッドを使用して問題なくコントロールを追加していましたが、これではできません。

4

3 に答える 3

12

別のスレッドから UI スレッドを更新することはできません。

 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);
            }
        }
于 2013-02-07T12:25:09.433 に答える
6

別のスレッドから UI スレッドに安全にアクセスするには、BeginInvoke を使用する必要があります。

    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);
    }));
于 2013-02-07T12:21:12.947 に答える
3

別のスレッドから親コントロールにコントロールを追加しようとしています。コントロールは、作成されたスレッドの親コントロールからのみ親コントロールに追加できます。

Invokeを使用して、別のスレッドからUIスレッドに安全にアクセスします。

    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);
    });
于 2013-02-07T12:17:46.640 に答える