C# Delegate 异步调用
namespace ConsoleApplication22 { /// /// 异步操作 /// /// /// /// //internal Func<int,int,int> int MainRun(int data, int sleep); internal class Program { private static void Main(string[] args) { Func<int,int,int> mainRun = TakeAWhile; var ar = mainRun.BeginInvoke(1, 100, null, null); while (!ar.IsCompleted) { Console.WriteLine("."); Thread.Sleep(100); } int result = mainRun.EndInvoke(ar); Console.WriteLine("Result :{0}", result); Console.ReadLine(); } private static int TakeAWhile(int data, int sleep) { Console.WriteLine("TakesAWhile stated"); Thread.Sleep(sleep); Console.WriteLine("TakesAWhile completed"); return ++data; } } }
namespace AsyncDelegateDemo { delegate String AsyncFooDelegate(int i,int sleep); class Program { /// <summary> /// 输出当前线程的信息 /// </summary> /// <param name="name">方法名称</param> static void PrintCurrThreadInfo(string name) { Console.WriteLine(name+ " is: " + Thread.CurrentThread.ManagedThreadId+ ", current " + (Thread.CurrentThread.IsThreadPoolThread ? "YES" : "NO ")); } /// <summary> /// 测试方法,Sleep一定时间 /// </summary> /// <param name="i">Sleep的时间</param> /// <param name="sleep"></param> static string Foo(int i,int sleep) { PrintCurrThreadInfo("Foo()"); Thread.Sleep(i); return i.ToString(); } /// <summary> /// 投递一个异步调用 /// </summary> static void PostAsync(int i) { AsyncFooDelegate caller = Foo; caller.BeginInvoke(i,1000, FooCallBack, caller); } static void Main2(string[] args) { PrintCurrThreadInfo("Main()"); for(int i = 0; i < 10 ; i++) { PostAsync(i); } Console.ReadLine(); } static void FooCallBack(IAsyncResult ar) { AsyncFooDelegate caller = (AsyncFooDelegate) ar.AsyncState; var index = caller.EndInvoke(ar); PrintCurrThreadInfo("FooCallBack()="+index); } } }