using System; using System.Collections; using System.Threading;
namespace tests { public class AsyncTest { public delegate void mydelegate<T>(T t);
/// <summary> /// 匹配委托,就是确定那个委托指向的函数需要异步 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="AR"></param> public void callbackFunction<T>(IAsyncResult AR) { mydelegate<T> mydelegate = ((mydelegate<T>)AR.AsyncState); mydelegate.EndInvoke(AR); }
/// <summary> /// 第一个业务方法 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="t"></param> public void print<T>(T t) { if (t is ICollection) { ICollection It = (ICollection)t; IEnumerator ie = It.GetEnumerator(); while(ie.MoveNext()) { Console.Write (ie.Current+" "); } Console.WriteLine(); } else { Console.WriteLine(false+" "+t.ToString()); } }
/// <summary> /// 第二个业务方法 /// </summary> /// <param name="i"></param> public void add(int i) { Console.WriteLine(i * 2); } /// <summary> /// 执行异步线程方法 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="t"></param> public void exeAsync<T>(T t, mydelegate<T> my) { AsyncCallback callback = new AsyncCallback(callbackFunction<T>); ///t 为 线程需要执行的参数; callback 功能 匹配委托,就是确定那个委托指向的函数需要异步 my 作为匹配的依据 my.BeginInvoke( t ,callback , my); } public static void Main() { AsyncTest at = new AsyncTest(); mydelegate<string[]> my1 = new mydelegate<string[]>(at.print<string[]>); mydelegate<int> my2 = new mydelegate<int>(at.add); at.exeAsync<int>(1111,my2); at.exeAsync<string[]>(new string[] { "aa", "b"}, my1); Thread.Sleep(100); } } }