class Program { static void Main(string[] args) { Console.WriteLine($"主线程:{Thread.CurrentThread.ManagedThreadId}"); var obj = new MyTestClass(); obj.TaskFinished += Obj_TaskFinished; obj.CallWithSync(5); //同步方式 obj.CallWithAsyncAction(10); //异步方式,但不用获取异步方法的返回值 obj.CallWithAsyncFunc(10); obj.CallWithAsync2Func(10);//异步方式,需要获取异步方法的返回值 Console.ReadKey(); } private static void Obj_TaskFinished(int value) { Console.WriteLine($"事件回调,线程:{Thread.CurrentThread.ManagedThreadId}, 运行结果:{value}"); } } public class MyTestClass { public event Action<int> TaskFinished; private void BusyTaskFunction(int value) { Console.WriteLine("-----------------"); Console.WriteLine($"任务开始,线程:{Thread.CurrentThread.ManagedThreadId}"); for (int i = 0; i < 30; i++) { Thread.Sleep(100); } Console.WriteLine($"BusyTaskFunction 运行完成。value={value}---------------"); } private int BusyTaskFunction2(int value) { int v = value * value; Console.WriteLine("-----------------"); Console.WriteLine($"任务开始,线程:{Thread.CurrentThread.ManagedThreadId}"); for (int i = 0; i < 30; i++) { Thread.Sleep(100); } Console.WriteLine($"BusyTaskFunction 运行完成。value={v}---------------"); return v; } public void CallWithSync(int value) { BusyTaskFunction(value); } /// <summary> /// 不用获取异步方法的返回值 /// </summary> /// <param name="value"></param> public void CallWithAsyncAction(int value) { Action<int> action = new Action<int>(BusyTaskFunction); action.BeginInvoke(value, o => { Console.WriteLine($"线程:{Thread.CurrentThread.ManagedThreadId} 任务结束,想干啥就干啥。"); TaskFinished?.Invoke(value); Console.WriteLine($"======================================"); }, null ); } public void CallWithAsyncFunc(int value) { Func<int, int> func = new Func<int, int>(BusyTaskFunction2); func.BeginInvoke(value, o => { Console.WriteLine($"线程:{Thread.CurrentThread.ManagedThreadId} 任务结束,想干啥就干啥。"); TaskFinished?.Invoke(value); Console.WriteLine($"======================================"); }, null ); } /// <summary> /// 去获取异步方法的返回值 /// </summary> /// <param name="value"></param> public void CallWithAsync2Func(int value) { Func<int, int> func = new Func<int, int>(BusyTaskFunction2); IAsyncResult ar = func.BeginInvoke(value, o => { int v1 = func.EndInvoke(o); Console.WriteLine($"线程:{Thread.CurrentThread.ManagedThreadId} 任务结束,想干啥就干啥。得到返回值{v1}"); TaskFinished?.Invoke(v1); Console.WriteLine($"======================================"); }, this ); } }