BOS*_*OSS 5 c# user-interface controls multithreading
我正在运行一个线程,该线程抓取信息并创建标签并显示它,这是我的代码
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();
}
Run Code Online (Sandbox Code Playgroud)
有趣的是,我有一个以前的应用程序有一个面板,我曾经使用线程添加控件没有任何问题,但这一个不会让我这样做.
Igo*_*goy 10
您无法从另一个线程更新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);
}
}
Run Code Online (Sandbox Code Playgroud)
您需要使用BeginInvoke从另一个线程安全地访问UI线程:
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);
}));
Run Code Online (Sandbox Code Playgroud)