UserControl call does not work

I have a form ( MainPage ), and I set UserControl several times in it, so I write a method in this form similar to this to call:

 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 inherits from UserControl , which my UserControls inherits from UIPart .

This method starts as follows:

 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*/ } ... } 

Error:

Cross-threading is not valid: the "MainPage" control is accessible from a thread other than the thread on which it was created.

I found a lot of questions and a lot of answers here about this error, but I can’t understand why it rushes to _frmMain.Show(); ? Should I call something else? Or I'm wrong? Is this related to creating the Handle of my UserControl?

+5
source share
2 answers

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 with aMethodCaller ()

The following is 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(); } } 
+2
source

_frmMain.Show() not guarded by any verification of call requirements. Therefore, you probably call it a background thread.

+1
source

All Articles