用委托开启线程的前提是:创建项目时必须选择“.NET Framework",如果选择的是”.Net Core“,在调用BeginInvoke时,系统会报错”Operation is not supported on this platform.“。
异步调用的另一个前提是:委托的方法列表中只能包含一个方法。
等待至完成
通过BeginInvoke和EndInvoke实现。
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading;usingSystem.Threading.Tasks;namespaceFrameworkDemo{publicdelegatelongMyDel(int a,int b);classProgram{staticlongsum(int a,int b){
Thread.Sleep(10*1000);return a + b;}staticvoidMain(string[] args){// 异步委托操作描述IAsyncResult res =null;long result =0;AsyncCallback callback = ar =>{// 输出结果:“计算结果为:11”
Console.WriteLine($"{ar.AsyncState}:{result}");};MyDel del =newMyDel(sum);// BeginInvoke开启异步调用// res的打印结果为System.Runtime.Remoting.Messaging.AsyncResult
res = del.BeginInvoke(3,8, callback,"计算结果为");// 等待线程结束,并获取返回值
result = del.EndInvoke(res);
Console.ReadLine();}}}