我正在运行一个线程,该线程获取信息并创建标签并显示它,这是我的代码
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();
}
有趣的是,我以前有一个带有面板的应用程序,我曾经使用线程向其添加控件,没有任何问题,但这个应用程序不允许我这样做。
您无法从另一个线程更新 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);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)