using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Text; using System.Threading; using System.Threading.Tasks; namespace 异步委托有返回值 { class Program { static void Main(string[] args) { Func<int, int, string> FuncTest = (a, b) => { Console.WriteLine("异步线程ID:" + Thread.CurrentThread.ManagedThreadId); return (a + b).ToString(); }; IAsyncResult rs = FuncTest.BeginInvoke(100, 100, CallBackTest, "传给回调方法的参数"); Console.WriteLine("主线程ID:" + Thread.CurrentThread.ManagedThreadId); Console.ReadKey(); } public static void CallBackTest(IAsyncResult a) { AsyncResult ia = (AsyncResult)a;//强制转换接口对象 var ob = (Func<int, int, string>)ia.AsyncDelegate;//获取在其上调用异步调用的委托对象,强转换成委托类型 string str = ob.EndInvoke(a);//取BeginInvoke返回值。 Console.WriteLine("回调线程方法ID:" + Thread.CurrentThread.ManagedThreadId + "返回值:" + str.ToString()); Console.WriteLine(a.AsyncState);//接收传入的参数,也就是BeginInvoke方法倒数第一个参数 } } }