非专业程序员

  :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

多线程使用TextBox控件  
        //声明一个委托
        public delegate void SetTextBoxValue(string value);

        //委托使用文本框
        void SetMyTextBoxValue(string value)
        {
            // Control.InvokeRequired 属性: 获取一个值,该值指示调用方在对控件进行方法调用时是否必须调用 Invoke 方法,因为调用方位于创建控件所在的线程以外的线程中。当前线程不是创建控件的线程时为true,当前线程中访问是False
            if (this.TextBoxControl.InvokeRequired)
            {
                SetTextBoxValue objSetTextBoxValue = new SetTextBoxValue(SetMyTextBoxValue);

                // IAsyncResult 接口:表示异步操作的状态。不同的异步操作需要不同的类型来描述,自然可以返回任何对象。
                // Control.BeginInvoke 方法 (Delegate):在创建控件的基础句柄所在线程上异步执行指定委托。
                IAsyncResult result = this.TextBoxControl.BeginInvoke(objSetTextBoxValue, new object[]{ value });
                try {
                    objSetTextBoxValue.EndInvoke(result);
                }
                catch {
                }
            }
            else
            {
                this.TextBoxControl.Text += value + Environment.NewLine;
                this.TextBoxControl.SelectionStart = this.TextBoxControl.TextLength;
                this.TextBoxControl.ScrollToCaret();
            }
        }

 


示例代码:
        public TestForm()
        {
            InitializeComponent();
        }

        private delegate void SetTextBoxValue(string value);

        private void SetMyTextBoxValue(string value)
        {
            if (this.TextBoxControl.InvokeRequired)
            {
                SetTextBoxValue objSetTextBoxValue = new SetTextBoxValue(SetMyTextBoxValue);
                IAsyncResult result = this.TextBoxControl.BeginInvoke(objSetTextBoxValue, new object[] { value });
                try
                {
                    objSetTextBoxValue.EndInvoke(result);
                }
                catch
                {
                }
            }
            else
            {
                this.TextBoxControl.Text += value + Environment.NewLine;
                this.TextBoxControl.SelectionStart = this.TextBoxControl.TextLength;
                this.TextBoxControl.ScrollToCaret();
            }
        }

        private void ExecuteNewThread()
        {
            for (int i = 0; i < 1000; i++)
            {
                SetMyTextBoxValue(i.ToString());
            }
        }

        private void NewThreadButton_Click(object sender, EventArgs e)
        {
            Thread objThread = new Thread(new ThreadStart(ExecuteNewThread));
            objThread.IsBackground = true;
            objThread.Start();
        }
    }

 

posted on 2010-08-03 22:55  曲仁岗  阅读(717)  评论(0编辑  收藏  举报