“Cross-thread operation not valid” exception on inner controls

前端 未结 7 1498
南方客
南方客 2020-12-19 05:36

I\'ve been struggling with this for quite a while: I have a function designed to add control to a panel with cross-thread handling, the problem is that though the panel and

7条回答
  •  长情又很酷
    2020-12-19 06:08

    Here is a small snippet of the full program:

    public class ucFoo : UserControl
    {
        private Panel pnlFoo = new Panel();
    
        public ucFoo()
        {
            this.Controls.Add(pnlFoo);
        }
    }
    
    public class ucFoo2 : UserControl
    {
        private Panel pnlFooContainer = new Panel();
    
        public ucFoo2()
        {
             this.Controls.Add(pnlFooContainer);
             Thread t = new Thread(new ThreadStart(AddFooControlToFooConatiner());
             t.Start()
        }
    
        private AddFooControlToFooConatiner()
        {
             ucFoo foo = new ucFoo();
             this.pnlFooContainer.Controls.Add(ucFoo); //<-- this is where the exception is raised
        }
    }
    

提交回复
热议问题