关于不同线程访问控件

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;//内部线程设置文本内容
            }
        }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,142评论 25 708
  • 1、问题来由 C#多线程操作的时候会发生共享违例,当然可以使用铺货异常的方法禁止掉,但这可能导致控件显示异常。 当...
    Shawn是个工程师阅读 1,842评论 0 6
  • 一、虚表、虚指针、动态绑定 这一部分,我们介绍下 继承体系下,类和对象的存储形式。 1.1 vptr 虚指针 和 ...
    Kidyours阅读 252评论 0 0
  • 据说凤凰网集体罢工了,都是些精英中的精英,不跟老板干了,是因为黑了大半天却成了老板的工具么?还是老板学会了黑他的人...
    写字人已失踪阅读 103评论 0 0
  • 今天是大年初二,一如既往的呆在家裡,吃完飯,和家人聊著天,心情很放鬆,享受著和家人在一起的時光,懷著崇敬的心給祖先...
    静心_安心阅读 143评论 0 0