玉祥平台客服-15087858732

标题: winform多线程调用控件 [打印本页]

作者: Adam丶鱼    时间: 2020-3-20 20:59
标题: winform多线程调用控件
本帖最后由 Adam丶鱼 于 2017-4-20 21:00 编辑

对多线程操作控件的理解:
控件不能被非创造他的线程修改。需调用控件.beginvoke,注入UI线程。
控件.beginvoke会把操作加入UI线程,阻塞画面响应。不要把耗时的计算放在控件.beginvoke里。即使多线程下,控件的更新是串行的。
UI线程对控件调用永远优先工作线程,即使开始的比工作线程晚,下例B比C早执行。
例子:
private void button1_Click(object sender, EventArgs e)
        {
           Thread th= new Thread(delegate()
            {
                for (int i = 0; i < 10; i++)
                {
                    System.Threading.Thread.Sleep(2000);//工作线程不阻塞UI线程
                    DoCreate_test(i);
                }
            });
            th.Start();
            richTextBox1.AppendText("\n" + System.Threading.Thread.CurrentThread.Name + ":" + "UI线程开始" + DateTime.Now);//代码A
            System.Threading.Thread.Sleep(4000);
            richTextBox1.AppendText("\n" + System.Threading.Thread.CurrentThread.Name + ":" + "UI线程结束" + DateTime.Now); //代码B
        }

        private delegate void FlushClient(int i);
        private static int a = 0;
        private void DoCreate_test(int cnt)
        {
            //非ui线程调用委托
            if (richTextBox1.InvokeRequired)
            {
                FlushClient fc = new FlushClient(DoCreate_test);
                this.BeginInvoke(fc,new object[]{cnt});
            }
            //ui线程直接操作
            else
            {
                //System.Threading.Thread.Sleep(2000); //错误写法阻塞UI线程
                richTextBox1.AppendText("\n" + System.Threading.Thread.CurrentThread.Name + ":" +(++a)); //代码C
            }
        }

作者: 张兴康    时间: 2020-3-21 14:14

作者: 张兴康    时间: 2020-3-21 14:14





欢迎光临 玉祥平台客服-15087858732 (http://bbs.delit.cn/) Powered by Discuz! X3.2