C#子线程操作UI线程更新报线程间操作无效

 //线程间操作无效=======NG
        private void button1_Click(object sender, EventArgs e)
        {
            Thread t = new Thread(RunWorkerThread);
            t.Start();
        }

         void RunWorkerThread(Object o)
        {
            SetBackground(null);
        }

         void SetBackground(Object o)
        {
            //this.BackColor = Brushes.Red;

            this.BackColor = System.Drawing.SystemColors.ButtonFace;
        }


        //线程间操作有效=======OK
        private void button2_Click(object sender, EventArgs e)
        {
            Thread t = new Thread(RunWorkerThread11);
            t.Start(SynchronizationContext.Current);//传入当前的同步上下文
        }
         void RunWorkerThread11(Object o)
        {
            //使用传入的上下文把消息发送到原来的线程上去
            SynchronizationContext sc = o as SynchronizationContext;
            sc.Post(SetBackground11, null);
        }

         void SetBackground11(Object o)
        {
           this. BackColor = System.Drawing.SystemColors.ActiveCaptionText;
        }

猜你喜欢

转载自blog.csdn.net/u014090257/article/details/127683090
今日推荐