C#中Invoke和BeginInvoke的区别

时间:2023-03-09 01:28:10
C#中Invoke和BeginInvoke的区别

1、Invoke() 调用时,Invoke会阻止当前主线程的运行,等到 Invoke() 方法返回才继续执行后面的代码,表现出“同步”的概念。

2、BeginInvoke() 调用时,当前线程会启用线程池中的某个线程来执行此方法,BeginInvoke不会阻止当前主线程的运行,而是等当前主线程做完事情之后再执行BeginInvoke中的代码内容,表现出“异步”的概念。在想获取 BeginInvoke() 执行完毕后的结果时,调用EndInvoke() 方法来获取。而这两个方法中执行的是一个委托。

测试代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks; namespace InvokeDemo
{
class Program
{
//代理
private delegate int Mydelegate(int a, int b); static void Main(string[] args)
{
Console.WriteLine("Invoke开始,时间:" + DateTime.Now);
Console.WriteLine("主线程ID:" + Thread.CurrentThread.ManagedThreadId);
Mydelegate myd = new Mydelegate(Fun);
var result = myd.Invoke(, );
Console.WriteLine("计算结果:" + result);
Console.WriteLine("Invoke结束,时间:" + DateTime.Now); Console.WriteLine();
Console.WriteLine("------分割线------");
Console.WriteLine(); Console.WriteLine("BeginInvoke开始,时间:" + DateTime.Now);
Mydelegate mydSync = new Mydelegate(Fun);
mydSync.BeginInvoke(, , new AsyncCallback(AsyncCallback), mydSync);
Console.WriteLine("BeginInvoke结束,时间:" + DateTime.Now); Console.Read();
} static int Fun(int a, int b)
{
Thread.Sleep();
Console.WriteLine("方法线程ID:" + Thread.CurrentThread.ManagedThreadId);
return a + b;
} static void AsyncCallback(IAsyncResult asyncResult)
{
var del = (Mydelegate)asyncResult.AsyncState;
var funResult = del.EndInvoke(asyncResult);
Console.WriteLine("计算结果:" + funResult);
}
}
}

结果:

C#中Invoke和BeginInvoke的区别

可以看出:

Invoke方法中线程ID跟主线程ID一致,表现是阻塞的。

InvokeBegin方法中线程ID跟主线程ID不一致,表现是异步的。