美文网首页
关于不同线程访问控件

关于不同线程访问控件

作者: 暗夜晴空 | 来源:发表于2017-08-08 19:35 被阅读0次

msdn上的一段代码

// This method demonstrates a pattern for making thread-safe
        // calls on a Windows Forms control. 
        //
        // If the calling thread is different from the thread that
        // created the TextBox control, this method creates a
        // SetTextCallback and calls itself asynchronously using the
        // Invoke method.
        //
        // If the calling thread is the same as the thread that created
        // the TextBox control, the Text property is set directly. 
        delegate void SetTextCallback(string text);//内部线程委托
        private void SetText(string text)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (this.textBox1.InvokeRequired)//判断是否是内部线程调用
            {   
                SetTextCallback d = new SetTextCallback(SetText);//外部线程创建委托
                this.Invoke(d, new object[] { text });//使用委托进行递归调用
            }
            else
            {
                this.textBox1.Text = text;//内部线程设置文本内容
            }
        }

相关文章

网友评论

      本文标题:关于不同线程访问控件

      本文链接:https://www.haomeiwen.com/subject/fhrxrxtx.html