我有这段代码:
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不会出现。
有什么问题?
答案 0 :(得分:1)
问题是,您在另一个Thread
中创建控件而不是GUI运行。BackgroundWorker
有一个事件RunworkerCompleted
,在DoWork
事件处理程序之后触发完成。 RunworkerCompleted
然后在调用Thread
的{{1}}中运行(在您的情况下是主线程)。因此,您在DoWork
和DoWork
中的GUI内容中执行所有与GUI无关的工作:
RunWorkerCompleted