gpt4 book ai didi

c# - "Cross-thread operation not valid"内部控件异常

转载 作者:太空狗 更新时间:2023-10-29 20:06:35 26 4
gpt4 key购买 nike

我已经为此苦苦挣扎了很长一段时间:我有一个功能旨在通过跨线程处理将控件添加到面板,问题是尽管面板和控件处于“InvokeRequired=false”中 - 我收到一个异常告诉我其中一个控件内部控件被访问从创建它的线程以外的线程,片段是这样的:

public delegate void AddControlToPanelDlgt(Panel panel, Control ctrl);
public void AddControlToPanel(Panel panel, Control ctrl)
{
if (panel.InvokeRequired)
{
panel.Invoke(new AddControlToPanelDlgt(AddControlToPanel),panel,ctrl);
return;
}
if (ctrl.InvokeRequired)
{
ctrl.Invoke(new AddControlToPanelDlgt(AddControlToPanel),panel,ctrl);
return;
}
panel.Controls.Add(ctrl); //<-- here is where the exception is raised
}

异常信息是这样的:

"Cross-thread operation not valid: Control 'pnlFoo' accessed from a thread other than the thread it was created on"

('pnlFoo' 在 ctrl.Controls 下)

如何将 ctrl 添加到面板?!


当代码到达“panel.Controls.Add(ctrl);”时行 - 面板和 ctrl 的“InvokeRequired”属性都设置为 false,问题是 ctrl 内的控件将“InvokeRequired”设置为 true。澄清一下:“面板”是在基础线程上创建的,“ctrl”是在新线程上创建的,因此,必须调用“面板”(导致“ctrl”需要再次调用)。一旦两个调用都完成,它就会到达 panel.Controls.Add(ctrl) 命令(“面板”和“ctrl”都不需要在此状态下调用)

这是完整程序的一小段:

public class ucFoo : UserControl
{
private Panel pnlFoo = new Panel();

public ucFoo()
{
this.Controls.Add(pnlFoo);
}
}

public class ucFoo2 : UserControl
{
private Panel pnlFooContainer = new Panel();

public ucFoo2()
{
this.Controls.Add(pnlFooContainer);
Thread t = new Thread(new ThreadStart(AddFooControlToFooConatiner());
t.Start()
}

private AddFooControlToFooConatiner()
{
ucFoo foo = new ucFoo();
this.pnlFooContainer.Controls.Add(ucFoo); //<-- this is where the exception is raised
}
}

最佳答案

顺便说一句 - 为了让自己不必创建无数委托(delegate)类型:

if (panel.InvokeRequired)
{
panel.Invoke((MethodInvoker) delegate { AddControlToPanel(panel,ctrl); } );
return;
}

此外,这现在对 AddControlToPanel 的内部调用进行定期静态检查,因此您不会弄错。

关于c# - "Cross-thread operation not valid"内部控件异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/974317/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com