C#中異步回調函數(shù)用法實例
更新時間:2015年04月22日 10:27:59 作者:dingding
這篇文章主要介紹了C#中異步回調函數(shù)用法,實例分析了異步回調函數(shù)的定義及使用技巧,具有一定參考借鑒價值,需要的朋友可以參考下
本文實例講述了C#中異步回調函數(shù)用法。分享給大家供大家參考。具體如下:
static void Main(string[] args)
{
Func<string,string> showMessage = ShowMessage;
//設置了回調函數(shù)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#程序設計有所幫助。
相關文章
常用.NET工具(包括.NET可再發(fā)行包2.0)下載
常用.NET工具(包括.NET可再發(fā)行包2.0)下載...2007-03-03
C#基于正則表達式刪除字符串中數(shù)字或非數(shù)字的方法
這篇文章主要介紹了C#基于正則表達式刪除字符串中數(shù)字或非數(shù)字的方法,涉及C#針對數(shù)字的簡單正則匹配相關操作技巧,需要的朋友可以參考下2017-06-06

