I have a form (MainPage
) and I set a UserControl
in it some times, So I write a method in that form like this to invoke:
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;
}
UIPart
class inherit from UserControl
that my UserControls inherit from UIPart
.
This method and invoke launched like this:
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*/
}
...
}
The error is:
Cross-thread operation not valid: Control 'MainPage' accessed from a thread other than the thread it was created on.
I found many questions and many answers here about this error, But I can't figure it out why it is throwing at _frmMain.Show();
?, Should I invoke something else? Or Am I in a wrong way? Is it related to creation of Handle of my UserControl?
Try adding the following code:
public static void aMethodCaller(){
if (_frmMain.InvokeRequired)
_frmMain.Invoke(new Action(aMethod));
else
aMethod();
}
and replace all references to aMethod() in your code to aMethodCaller()
Below is the sample code:
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();
}
}
The _frmMain.Show()
isn't guarded by any invocation requirement check. So you're probably calling it in a background thread.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With