winform中如何在多线程中更新UI控件--ListView实时显示执行信息

1、在winform中,所有对UI的操作,都得回到UI线程(主线程)上来,才不会报错

      线程间操作无效: 从不是创建控件的线程访问它。

2、在winform中,允许通过Control.invoke对控件进行操作。如下代码:

private void btnTest_Click(object sender, EventArgs e)
        {           
            CheckA();           
        }        

 
        private void CheckA()
        {
            System.Threading.ThreadPool.QueueUserWorkItem(t => {
                ShowInfo("检测开始.....");
                System.Threading.Thread.Sleep(3000);
                ShowInfo("暂停3秒结束.....");
                System.Threading.Thread.Sleep(2000);
                ShowInfo("暂停2秒结束.....");
                System.Threading.Thread.Sleep(1000);
                ShowInfo("检测结束");
            });
                       
        }
        private void ShowInfo(string Info)
        {
            listView1.Invoke(new Action(() =>
            {
                listView1.Columns[0].Width = listView1.ClientSize.Width;
                listView1.Items.Insert(0, new ListViewItem(Info));
            }));            
        }  

  

 

posted @ 2018-09-30 17:36  早起Abc  阅读(1099)  评论(0编辑  收藏  举报