从BackgroundWorker创建控件

时间:2017-07-01 13:07:45

标签: c# backgroundworker

我有这段代码:

    public Form1()
    {
        InitializeComponent();

        BackgroundWorker bw = new BackgroundWorker();
        bw.WorkerSupportsCancellation = true;
        bw.WorkerReportsProgress = true;
        bw.DoWork += (s, ev) => show();
        bw.RunWorkerAsync();
    }

    private void show()
    {
        MessageBox.Show("aaaaaa");

        PictureBox load = new PictureBox();
        load.BackColor = Color.White;
        load.Width = this.Width;
        load.Height = this.Height;
        load.Left = 0;
        load.Top = 0;
        load.Name = "load";

        this.Controls.Add(load);
        load.BringToFront();

        MessageBox.Show("bbbbb");
    }

不会创建PictureBox而且" bbbbb" MessageBox不会出现。

有什么问题?

1 个答案:

答案 0 :(得分:1)

问题是,您在另一个Thread中创建控件而不是GUI运行。BackgroundWorker有一个事件RunworkerCompleted,在DoWork事件处理程序之后触发完成。 RunworkerCompleted然后在调用Thread的{​​{1}}中运行(在您的情况下是主线程)。因此,您在DoWorkDoWork中的GUI内容中执行所有与GUI无关的工作:

RunWorkerCompleted