namespace invoke和begininvoke的用法 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } //声明接受int的方法并返回空的委托。 public delegate void invokeDelegate(); //调用委托, // invokeDelegate FF = new invokeDelegate(StartMethod); private void button1_Click(object sender, EventArgs e) { MessageBox.Show(Thread.CurrentThread.GetHashCode().ToString() + "主线程1 最先执行"); // 最先执行 Thread invokeThread = new Thread(new ThreadStart(StartMethod)); //委托创建线程 invokeThread.Start(); //开始线程 string a = string.Empty; for (int i = 0; i < 10; i++) //调整循环次数,看的会更清楚 { Thread.Sleep(1000); a = a + "循环执行"; } MessageBox.Show(Thread.CurrentThread.GetHashCode().ToString() +"主线程1"+ a); } private void StartMethod() { MessageBox.Show(Thread.CurrentThread.GetHashCode().ToString() + "主线程1 第二执行"); button1.Invoke(new invokeDelegate(invokeMethod)); //传递一个委托的方法; 依赖此控件来执行委托 //Thread.Sleep(3000); MessageBox.Show(Thread.CurrentThread.GetHashCode().ToString() + "子线程1"); } private void invokeMethod() { //Thread.Sleep(5000); MessageBox.Show(Thread.CurrentThread.GetHashCode().ToString() + "主线程1 _执行委托方法"); } } }
来源 https://www.cnblogs.com/lsgsanxiao/p/5523282.html;