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

前端 未结 7 1457
南方客
南方客 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:23

    Here is a working piece of code :

    public delegate void AddControlToPanelDlg(Panel p, Control c);
    
            private void AddControlToPanel(Panel p, Control c)
            {
                p.Controls.Add(c);
            }
    
            private void AddNewContol(object state)
            {
                object[] param = (object[])state;
                Panel p = (Panel)param[0];
                Control c = (Control)param[1]
                if (p.InvokeRequired)
                {
                    p.Invoke(new AddControlToPanelDlg(AddControlToPanel), p, c);
                }
                else
                {
                    AddControlToPanel(p, c);
                }
            }
    

    And here is how I tested it. You need to have a form with 2 buttons and one flowLayoutPanel (I chose this so I didn't have to care about location hwhen dinamically adding controls in the panel)

    private void button1_Click(object sender, EventArgs e)
            {
                AddNewContol(new object[]{flowLayoutPanel1, CreateButton(DateTime.Now.Ticks.ToString())});
            }
    
            private void button2_Click(object sender, EventArgs e)
            {
                ThreadPool.QueueUserWorkItem(new WaitCallback(AddNewContol), new object[] { flowLayoutPanel1, CreateButton(DateTime.Now.Ticks.ToString()) });
            }
    

    I that he probem with your exaple is that when you get in the InvokeRequired branch you invoke the same function wou are in, resulting in a strange case of recurssion.

    0 讨论(0)
提交回复
热议问题