C#中異步回調函數用法實例。本站提示廣大學習愛好者:(C#中異步回調函數用法實例)文章只能為提供參考,不一定能成為您想要的結果。以下是C#中異步回調函數用法實例正文
本文實例講述了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#法式設計有所贊助。