none
Adding controls to a panel in thread safe way RRS feed

  • Question

  • Hi,
     
    I am developing a WinForms application. Currently it is single-threaded but I would like to make it multi threaded. I am having a problem with this function:

     private void AddToPanel(Panel p, Control c)  
            {  
                p.Controls.Clear();  
                p.Controls.Add(c);  
            } 

    In single threaded mode this function dynamically adds controls to a panel and works just fine.

    When I use it from multi threaded application it throws an exception Illegal cross-thread operation.

    I tried to solve this with delegate but I could not make it to work. The problem here is that controls were created in different threads initially.

    Is there a way to solve this?

    Thanks, Frenki
    Saturday, August 9, 2008 4:01 PM

Answers

  • Creating forms on another thread is a great way to get in trouble like this.  Still, using p.Invoke() instead of this.Invoke() should work.
    Hans Passant.
    • Marked as answer by Zhi-Xin Ye Thursday, August 14, 2008 2:03 PM
    • Marked as answer by Zhi-Xin Ye Thursday, August 14, 2008 2:03 PM
    Saturday, August 9, 2008 7:46 PM
    Moderator

All replies

  • > I tried to solve this with delegate but I could not make it to work. The problem here is that controls were created in different threads initially.

    I think you should find a way so that your delegate/callback can create the controls.  This may involve passing more data to the callback than you are currently doing.

    Note that the forum for Windows Forms questions is: http://forums.microsoft.com/msdn/showforum.aspx?forumid=8&siteid=1
    Saturday, August 9, 2008 4:13 PM
  • Creating forms on another thread is a great way to get in trouble like this.  Still, using p.Invoke() instead of this.Invoke() should work.
    Hans Passant.
    • Marked as answer by Zhi-Xin Ye Thursday, August 14, 2008 2:03 PM
    • Marked as answer by Zhi-Xin Ye Thursday, August 14, 2008 2:03 PM
    Saturday, August 9, 2008 7:46 PM
    Moderator