MethodInvoker委托,跨线程访问


    Invoke(new MethodInvoker(delegate
     {
        textBox1.Text = "修改了";
    })); 

在子线程中想要操作主线程中的变量值,可以通过此方法修改。

如:线程异步工作时,达到某个条件修改某个文本框中的内容。

上面是简单缩写,也可以写成:

    private void btnOK_Click(object sender, EventArgs e)
         {
             Thread td new Thread(new ThreadStart(threadRun));
             td.Start();
         }

         /// 
         /// 主线程要执行的方法
         /// 
         private void run()
         {
             this.textBox1.Text = "修改了";
         }

         /// 
         /// 子线程线程方法
         /// 
         private void threadRun()
         {
             MethodInvoker In new MethodInvoker(run);
             this.BeginInvoke(In);
         }