invoke和begininvoke

private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(Thread.CurrentThread.GetHashCode().ToString() + "AAA");
invokeThread = new Thread(new ThreadStart(StartMethod));
invokeThread.Start();
string a = string.Empty;
for (int i = 0; i < 3; i++) //调整循环次数,看的会更清楚
{
Thread.Sleep(1000);
a = a + "B";
}
MessageBox.Show(Thread.CurrentThread.GetHashCode().ToString() + a);
}
private void StartMethod()
{
MessageBox.Show(Thread.CurrentThread.GetHashCode().ToString() + "CCC");
button1.BeginInvoke(new invokeDelegate(invokeMethod));//Invoke 在拥有此控件的基础窗口句柄的线程上执行指定委托
//在创建控件的基础句柄所在线程上异步执行指定委托 BeginInvoke
//创建控件的基础窗口句柄其实就是主线程
//BeginInvoke和Invoke都是把委托提交给主线程,同步和异步其实是针对子线程而言的
//(invoke等待主线程完成自己任务,然后主线程再完成invoke提交的任务,然后子线程完成invoke语句之后的任务)
//(beginInvoke等待主线程完成自己任务,然后主线程再完成invoke提交的任务,然后子线程不必等待主线程继续完成invoke语句之后的任务)
//对比invoke和begininvoke发现,同步和异步是针对子线程而言的,子线程同步于主线程(顺序时间),子线程异步于主线程(平行时间)
MessageBox.Show(Thread.CurrentThread.GetHashCode().ToString() + "DDD");
}
private void invokeMethod()
{
//Thread.Sleep(3000);
MessageBox.Show(Thread.CurrentThread.GetHashCode().ToString() + "EEE");
}

猜你喜欢

转载自www.cnblogs.com/aaajing/p/12027431.html