C#中检测委托线程的结束

编程入门 行业动态 更新时间:2024-10-20 11:53:21

C#中检测委托<a href=https://www.elefans.com/category/jswz/34/1771240.html style=线程的结束"/>

C#中检测委托线程的结束

已知可以通过写一个while的死循环来检测线程是否结束(不要用
第二种方式为:

等待句柄

class Program{static int Test(int i, string str){Console.WriteLine("test"+i+str);Thread.Sleep(100);//让当前线程休眠(即模拟下载过程),单位是msreturn 42;}static void Main(){Func<int, string, int> a = Test;IAsyncResult ar = a.BeginInvoke(100, "hello", null, null);//IAsyncResult可以取得当前线程的状态——比如是否已经结束?Console.WriteLine("main");//检测线程的结束//如果在超时时间内线程结束了,就返回true,否则就返回falsebool 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);//让当前线程休眠(即模拟下载过程),单位是msreturn 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);//让当前线程休眠(即模拟下载过程),单位是msreturn 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表达式中获得结果     

更多推荐

C#中检测委托线程的结束

本文发布于:2024-03-14 18:44:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1737106.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   结束

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!