.net之线程控件之间访问

  public delegate void MyInvoke( );
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Thread th = new Thread(new ThreadStart(correctfunc));
            th.Start();          
        }
        public void func() {
            try
            {
                
                //.net 禁止从不是本身创建的线程调用。
                textBox1.Text = "会出错吗?";
            }
            catch (Exception e) {
                throw new Exception("error! "+e.Message.ToString());
            }
        }

        public void correctfunc() {
            try
            { 
            //先判断是否有其他线程调用!
                if (textBox1.InvokeRequired)
                {
                    MyInvoke my = new MyInvoke(correctfunc);
                    this.Invoke(my);
                }
                else
                {
                    textBox1.Text = "不会出错!";
                }
            }
            catch(Exception e){
                throw new Exception("error!"+e.Message.ToString());
            }
        }
    }
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
/**
 * 题目:用多线程实现进度条的滚动。
 * 
 * 假如有个100个事件,每一秒执行一个。当每执行一个事件需要在进度条上和静态框有标注。
 */
namespace WindowsApplication5
{
    public delegate void MyInvoke();
    public partial class Form1 : Form
    {

        TimeSpan t = new TimeSpan(0, 0, 1);
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ThreadStart ts=new ThreadStart(func1);
            ts+=func2;
            ts += func3;
            Thread th = new Thread(ts);
            th.Start();
        }


        void func1(){
            if (progressBar1.InvokeRequired)
            {
                MyInvoke my = new MyInvoke(func1);
                this.Invoke(my);
            }
            {
                Thread.Sleep(t);
                progressBar1.Value = 33;
            }
        }
        void func2() {
            if (progressBar1.InvokeRequired)
            {
                MyInvoke my = new MyInvoke(func2);
                this.Invoke(my);
            }
            {
                Thread.Sleep(t);
                progressBar1.Value =66;
            }
        }
        void func3() 
        {
            if (progressBar1.InvokeRequired)
            {
                MyInvoke my = new MyInvoke(func3);
                this.Invoke(my);
            }
            {
                Thread.Sleep(t);
                progressBar1.Value = 99;

            }
        }

    }
}
原文地址:https://www.cnblogs.com/canbefree/p/3502208.html