已知可以通过写一个while的死循环来检测线程是否结束(不要用)
第二种方式为:
等待句柄
class Program{
static int Test(int i, string str){
Console.WriteLine("test"+i+str);
Thread.Sleep(100);//让当前线程休眠(即模拟下载过程),单位是ms
return 42;
}
static void Main(){
Func<int, string, int> a = Test;
IAsyncResult ar = a.BeginInvoke(100, "hello", null, null);
//IAsyncResult可以取得当前线程的状态——比如是否已经结束?
Console.WriteLine("main");
//检测线程的结束
//如果在超时时间内线程结束了,就返回true,否则就返回false
bool isEnd = ar.AsyncWaitHandle.WaitOne(1000);//1000为设置的超时时间
if(isEnd)
{
int res = a.EndInvoke(ar);
Console.WriteLine(res);
}
}
第三种方法则为:
回调函数
class Program{
static int Test(int i, string str){
Console.WriteLine("test"+i+str);
Thread.Sleep(100);//让当前线程休眠(即模拟下载过程),单位是ms
return 42;
}
static void Main(){
Func<int, string, int> a = Test;
a.BeginInvoke(100, "hello", OnCallBack, a);
//这里需要注意的是,对于BeginInvoke方法,后面两个参数
//第一个参数表示一个委托,需要传递一个方法,当该线程结束时会调用这个方法
//第二个参数可以设置为任意对象,以便在回调函数中访问它,在这里所用的是上面定义的委托a
//例如可以设置为委托实例,这样就可以在回调方法中获取委托方法的结果
}
static void OnCallBack(IAsyncResult ar)//回调函数,参数是固定的
{
Func<int, string, int> a = ar.AsyncState as Func<int, string, int>;
int res = a.EndInvoke(ar);
Console.WriteLine(res+" 在回调函数中获取结果");
}
}
//输出为:
//test100hello
//42在回调函数中获取结果
利用lambda表达式来实现回调函数
class Program{
static int Test(int i, string str){
Console.WriteLine("test"+i+str);
Thread.Sleep(100);//让当前线程休眠(即模拟下载过程),单位是ms
return 42;
}
static void Main(){
Func<int, string, int> a = Test;
a.BeginInvoke(100, "hello", ar=>
{
int res = a.EndInvoke(ar);
Console.WriteLine(res+"在lambda表达式中获得结果"));
}, null);
}
}
//输出为
//test100hello
//42在lambda表达式中获得结果