Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoke of a UserControl doesn't work

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?

like image 348
shA.t Avatar asked Oct 19 '22 09:10

shA.t


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 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();
    }
}
like image 152
Denis Yarkovoy Avatar answered Nov 15 '22 06:11

Denis Yarkovoy


The _frmMain.Show() isn't guarded by any invocation requirement check. So you're probably calling it in a background thread.

like image 39
Yegor Avatar answered Nov 15 '22 06:11

Yegor