我知道我的问题有很多主题,但我找不到适合我的案例的解决方案...
我有一个面板,我在运行时在其上添加控件,我尝试了这段代码,但它对我没有帮助,并且出现错误:
cross-thread operation not valid control 'panel1' accessed from a thread other than the thread it was created on
这是我的代码:
public void AddControlToPanel(Panel panel, Control ctrl)
{
if (panel.InvokeRequired)
{
panel.Invoke((MethodInvoker)delegate { AddControlToPanel(panel, ctrl); });
return;
}
else
panel.Controls.Add(ctrl);
}
我这样调用它:
AddControlToPanel(panel1, ctrl);
最佳答案
您可以在项目的命名空间中创建一个控件扩展,如下所示:
public static class ControlExtensions
{
public static void UIThread(this Control @this, Action code)
{
if (null != @this && (<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ad8cedd9c5c4de83e9c4deddc2dec4c3ca" rel="noreferrer noopener nofollow">[email protected]</a> || <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c3e283b7abaab0ed8ab087aab0b3acb0a6a7" rel="noreferrer noopener nofollow">[email protected]</a>))
{
if (@this.InvokeRequired)
{
@this.BeginInvoke(code);
}
else
{
code.Invoke();
}
}
}
}
并在代码中使用它,如下所示:
this.UIThread(() =>
{
panel1.Controls.Add(ctrl);
});
关于c# - 跨线程操作无效控制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23339664/