shA*_*A.t 5 c# multithreading winforms
我有一个form(MainPage),并且我UserControl在其中设置了一些,所以我用这样的形式写一个方法来调用:
delegate void containerPanelCallback(UIPart uiPart);
public void IncludeUIPart(UIPart uiPart)
{
if (this.containerPanel.InvokeRequired)
{
containerPanelCallback d = new containerPanelCallback(IncludeUIPart);
containerPanel.Invoke(d, new object[] { uiPart });
}
else
{
containerPanel.Controls.Clear();
containerPanel.Controls.Add(uiPart);
}
uiPart.Size = this.containerPanel.Size;
uiPart.Dock = DockStyle.Fill;
}
Run Code Online (Sandbox Code Playgroud)
UIPartclass继承UserControl自我的UserControls继承自UIPart.
这个方法和调用启动如下:
public class myClass
{
...
private static MainPage _frmMain;
private static myUIPart6 UIP6;
...
public static void aMethod(/* Some arguments */)
{
UIP6 = new myUIPart6 { /* Some settings of properties */ };
_frmMain.IncludeUIPart(UIP6);
_frmMain.Show(); /*Throws an error*/
}
...
}
Run Code Online (Sandbox Code Playgroud)
错误是:
跨线程操作无效:控制从正在创建的线程以外的线程访问的"MainPage".
我在这里找到了很多关于这个错误的问题和许多答案,但我无法弄清楚它为什么会抛出_frmMain.Show();?,我应该调用别的东西吗?还是我错了?它与我的UserControl的Handle的创建有关吗?
尝试添加以下代码:
public static void aMethodCaller(){
if (_frmMain.InvokeRequired)
_frmMain.Invoke(new Action(aMethod));
else
aMethod();
}
Run Code Online (Sandbox Code Playgroud)
并将代码中对 aMethod() 的所有引用替换为 aMethodCaller()
下面是示例代码:
class Foo
{
static Form _frmMain;
public static void aMethod()
{
_frmMain.Show();
}
public static void aMethodCaller()
{
if (_frmMain.InvokeRequired)
_frmMain.Invoke(new Action(aMethod));
else
aMethod();
}
}
Run Code Online (Sandbox Code Playgroud)