problem calling methode with delegate

hi i have a problem communicating from a thread to the mainForm

i thought i could solve the problem by using a delegate 
but i get an exception

Controls created on one thread cannot be parented to a control on a different thread

the thing i am trying to do is to add a TabPage to a TabControl

i my mainForm 
...
public delegate void joinChannelDelegate(VyPacket packet);
private joinChannelDelegate joinChannelDel;

 mainforms constructor

joinChannelDel = new joinChannelDelegate(userJoins);
decode = new Decode(this,new PMCallback(visPrivateMessage),joinChannelDel);
recive = new Listen(decode);

in the recive object i am making a thread that listens for udp packets
and calls a methode in the decode object

methode in mainForm that the delegaten points to 

public void userJoins(VyPacket packet)
{
  bool eksists=false;
  //checks if channel exists
  foreach(Channel ch in channels)
  {
    if(ch.Name==packet.Channel)
    {
      eksists=true;
      break;
    }
  }
  if(!eksists)
  {
    Channel ch = new Channel(packet.Channel);
    channels.Add(ch);                
    tabControl1.TabPages.Add(ch);  //<--- Exception her 
  }
  
}


in Decode klassen 

private MainForm.joinChannelDelegate joinChannelCallback;


public Decode(MainForm.joinChannelDelegate joinChannelCallback)
{
    this.joinChannelCallback = joinChannelCallback;
}

... 
where i am calling the methode in mainForm throu the delegate 

joinChannelCallback(packet);




Answer this question

problem calling methode with delegate

  • HSS Guido

    Trying to alter the user interface in a thread other than the one that created it is a big no-no in Windows programming.

    Any method that does any UI manipulation, such as your userJoins method, must be called using Control.Invoke or Control.BeginInvoke when called from a non-UI thread.

    So, instead of calling your delegate directly, you'd do something like:

    this.Invoke(joinChannelCallback, new object[] { packet });

  • ShaneBough

    thanks for the help 
    i got it to work with invoke(..

    i dont realy understand what is hapening with the invoke
    is there some article where i can read more about invoke


  • Sunny Day

    This link was recently posted in the articles:

    <a href="http://weblogs.asp.net/justin_rogers/articles/126345.aspx">http://weblogs.asp.net/justin_rogers/articles/126345.aspx</a>


  • problem calling methode with delegate