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#程序设计有所帮助。
以上是 C#中异步回调函数用法实例 的全部内容, 来源链接: utcz.com/z/330380.html