深入浅出多线程系列之三:线程池

📅 2026/7/5 3:53:01
深入浅出多线程系列之三:线程池
借助Task Parallel Library(framework 4.0)调用ThreadPool.QueueUserWorkItem借助异步委托。借助BackgroundWorker.。下面的一些构造间接的使用了线程池:WCF,Remoting,Asp.net, asmx web services应用程序。System.Timers.Timer 和 System.Threading.Timer.framework的一些异步方法例如WebClient 类和大部分BeginXXX方法。PLINQ使用线程池的一些问题不可以设置一个线程池线程的名字。线程池线程全部都是后台线程。阻塞一个线程池线程可能会触发创建一个新线程除非你调用ThreadPool.SetMinThreads方法。通过Thread.CurrentThread.IsThreadPoolThread属性可以查询一个线程是否是线程池线程。实战ThreadPool1通过Task使用线程池publicstaticvoidMainThread(){TaskstringtaskTask.Factory.StartNewstring(()DownloadString(http://www.google.com));//DoSomethingstringresulttask.Result;}staticstringDownloadString(stringuri){using(var wcnewSystem.Net.WebClient())returnwc.DownloadString(uri);}当查询task.Result的时候线程阻塞等待task返回Result。2通过ThreadPool.QueueUserWorkItempublicstaticvoidMainThread(){ThreadPool.QueueUserWorkItem(Go);ThreadPool.QueueUserWorkItem(Go,123);Console.ReadLine();}staticvoidGo(objectdata){Console.WriteLine(Hello from the thread pool!data);}Output:Hello from the thread pool!Hello from the thread pool! 1233借助委托的BeginXXX方法publicstaticvoidMainThread(){Funcstring,intmethodWork;method.BeginInvoke(test, Done, method);}staticintWork(strings) {returns.Length; }staticvoidDone(IAsyncResult cookie){var target(Funcstring,int)cookie.AsyncState;intresulttarget.EndInvoke(cookie);Console.WriteLine(String length is:result);}在这里将method当作参数进行传递后在cookie的AsyncState中就可以使用传递的method了因为cookie.AsyncState类型是object所以需要进行转换然后调用EndInvoke方法来获取结果。