C#中Invoke与BeginInvoke的区别(另附使用循环创建多个线程)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace InvokeTest
{
delegate void MsgDelegate(String str);//声明一个代理
public partial class Form1 : Form
{
Thread[] threads = new Thread[10];//如果不使用关键字new出对象来,则会报“未将对象引用设置到对象的实例。”的错误
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Thread.CurrentThread.Name = "主线程";
for(int i=0;i<10;i++)
{
Thread ts = new Thread(new ThreadStart(threadProc));
ts.Name = "线程组成员"+i.ToString()+"号";
threads[i] = ts;
ts.IsBackground = true;
ts.Start();
}
}
private void showMsg(String str)
{
Thread.Sleep(5000);//线程休眠5秒...
MessageBox.Show(str+"是在"+Thread.CurrentThread.Name+"中执行的");//显示执行该代理函数的是哪个线程
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("执行A1代码段");
Thread T1 = new Thread(threadProc1);
T1.Name = "线程一";
T1.Start();
MessageBox.Show("执行B1代码段");
}
private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show("执行A2代码段");
Thread T2 = new Thread(threadProc2);
T2.Name = "线程二";
T2.Start();
MessageBox.Show("执行B2代码段");
}
/// <summary>
/// 线程一的线程函数
/// </summary>
private void threadProc1()
{
Invoke(new MsgDelegate(showMsg), new object[] { "通过Invoke调用showMsg" });//相当于this.Invoke,调用要消耗较长时间的代码后完了才开始执行下一条语句
MessageBox.Show("Invoke函数后调用,因为Invoke是同步执行的,所以刚才我一直在等待showMsg执行完呢,唉...");
}
/// <summary>
/// 线程二的线程函数
/// </summary>
private void threadProc2()
{
BeginInvoke(new MsgDelegate(showMsg), new object[] { "通过BeginInvoke调用showMsg" });//相当于this.BeginInvoke()调用要消耗较长时间的代码后立刻执行下一条语句
MessageBox.Show("BeginInvoke函数后调用,但由于BeginInvoke的异步执行,故还没等showMsg执行完我就被执行了!哈哈...");
}
private void threadProc()
{
MessageBox.Show(Thread.CurrentThread.Name+" 已经运行!");
}
}
}
C#中Invoke类似于C++中的SendMessage(),其会阻塞线程(即同步);而BeginInvoke类似于PostMessage(),其不会阻塞线程(即异步);