本文實例講述了C#中異步回調函數用法。分享給大家供大家參考。具體如下:
static void Main(string[] args){ Func<string,string> showMessage = ShowMessage; //設置了回調函數Completed,不能有返回值 IAsyncResult result = showMessage.BeginInvoke("測試異步委托",new AsyncCallback(Completed),null); //半段異步是否結束 while(!result.IsCompleted) { Console.WriteLine("主線程可以進行其它的操作!"); } Console.ReadLine();}static string ShowMessage(string x){ string current = string.Format("當前線程id為{0}",Thread.CurrentThread.ManagedThreadId); Thread.Sleep(3000); return string.Format("{0},輸入為{1}", current, x);}static void Completed(IAsyncResult result){ Console.WriteLine("異步完成!"); //獲取委托對象,并用EndInvoke方法獲取返回結果 AsyncResult _result = (AsyncResult) result; Func<string, string> showMessage = (Func<string, string>) _result.AsyncDelegate; //結束異步操作并輸出 Console.WriteLine(showMessage.EndInvoke(_result));}
希望本文所述對大家的C#程序設計有所幫助。
新聞熱點
疑難解答