版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lijianfex/article/details/78435511
Unity之C#——异步委托开启线程,三种方法检测结束
源码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace _004_异步委托开启线程
{
class Program
{
static int Test(int i, string str)
{
Console.WriteLine("我:lisan" + i + str);
Thread.Sleep(5000);//让当前线程休眠,单位毫秒 ms 模拟查询的等待过程
return 19960908;
}
static void Main(string[] args)
{
////1.利用循环检测线程结束
//Func<int, string, int> a = Test;
////开启一个新线程去执行 a委托的方法
//IAsyncResult ar = a.BeginInvoke(199610, "的生日是多少?",null, null);
////IAsyncResult 获取线程的当前状态
//Console.WriteLine("叮当:主人,请提问!");
//while (!ar.IsCompleted)
//{
// Thread.Sleep(10);//控制检测线程是否结束的频率,每10毫秒检测一次。
// Console.WriteLine("查询中。。。。。");
//}
//int res = a.EndInvoke(ar);
//Console.WriteLine("lisan199610的生日是:" + res);
//Console.ReadKey();
////2.利用回调函数检测线程结束
//Func<int, string, int> a = Test;
////开启一个新线程去执行 a委托的方法
//IAsyncResult ar = a.BeginInvoke(199610, "的生日是多少?", OnCallBack, a);
////IAsyncResult 获取线程的当前状态
//Console.WriteLine("叮当:主人,请提问!");
//Console.ReadKey();
//3.利用回调函数检测线程结束,并且回调函数用lambe表达式
Func<int, string, int> a = Test;
//开启一个新线程去执行a委托的方法
a.BeginInvoke(199610, "的生日是多少?",
ar =>
{
int res = a.EndInvoke(ar);
Console.WriteLine("叮当:lisan199610的生日是:" + res);
},null);
Console.WriteLine("叮当:主人,请提问!");
Console.ReadKey();
}
////2.回调函数
//static void OnCallBack(IAsyncResult ar)
//{
// Func<int, string, int> a = ar.AsyncState as Func<int, string, int>;
// int res = a.EndInvoke(ar);
// Console.WriteLine("叮当:lisan199610的生日是:" + res);
//}
}
}