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));
}
//csharp/6984