ThreadPool.RegisterWaitForSingleObject(wait, new WaitOrTimerCallback(test11), state, 5000, false)可以用来在线程完成,或者超时时,调用回调函数。
实例参考:
using System; using System.Threading; using static System.Console; using static System.Threading.Thread; namespace Chapter3.Recipe5 { class Program { static void Main(string[] args) { //RunOperations(TimeSpan.FromSeconds(5)); RunOperations(TimeSpan.FromSeconds(7)); Console.ReadLine(); } static void RunOperations(TimeSpan workerOperationTimeout) { using (var evt = new ManualResetEvent(false)) using (var cts = new CancellationTokenSource()) { WriteLine("Registering timeout operation..."); var worker = ThreadPool.RegisterWaitForSingleObject(evt , (state, isTimedOut) => WorkerOperationWait(cts, isTimedOut) //超时后,被调用的函数 , null , 8000 //超时值 , true); WriteLine("Starting long running operation..."); ThreadPool.QueueUserWorkItem(_ => WorkerOperation(evt)) //Sleep(workerOperationTimeout.Add(TimeSpan.FromSeconds(2))); //该语句的功能,就是让线程所在的函数没有运行结束,因为线程池中的线程,都是后台线程。 Sleep(15000); worker.Unregister(evt); } } static void WorkerOperation(ManualResetEvent evt) { for(int i = 0; i < 2; i++) { Sleep(TimeSpan.FromSeconds(1)); } evt.Set(); }
参考链接:
http://www.cnblogs.com/Kazaf/archive/2012/03/26/2417341.html
转载于:https://blog.51cto.com/acadia627/1972587