c# - 跨线程操作无效控制

标签 c# thread-safety invoke

我知道我的问题有很多主题,但我找不到适合我的案例的解决方案...

我有一个面板,我在运行时在其上添加控件,我尝试了这段代码,但它对我没有帮助,并且出现错误:

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/

相关文章:

c# - 重复一段代码来衡量它的执行时间有多稳健?

c# - 为什么在移位 32 位值时只使用移位操作数的低五位? (例如(UInt32)1 << 33 == 2)

multithreading - 套接字问题

c# - 我写了有趣的 Linq 代码,但我不知道它如何工作或为什么工作

c# - 从 WPF-TreeView 中选择 Rootnode

c# - cookie 在 c# 中不会过期

c# - C# 中的线程和 TcpListener

multithreading - 是否调用方法和函数

c# - 两个WinForm之间的TreeView的Invoke方法应该在哪里处理?

在创建窗口句柄之前,无法在控件上调用 VB.NET Invoke,但句柄已创建