上一篇文章我们总结了多线程最基础的知识点Thread,我们知道了如何开启一个新的异步线程去做一些事情。可是当我们要开启很多线程的时候,如果仍然使用Thread我们需要去管理每一个线程的启动,挂起和终止,显然是很麻烦的一件事情。还好.net framework为我们提供了线程池ThreadPool来帮助我们来管理这些线程,这样我们就不再需要手动地去终止这些线程。这一篇文章就让我们来学习一下线程池ThreadPool吧。关于它我想从以下几个方面进行总结。
ThreadPool类是一个静态类,你不能也不必要生成它的对象。而且一旦使用该方法在线程池中添加了一个项目,那么该项目是无法取消的。这里你无需自己建立线程,我们只需要把要做的工作写成函数,然后作为参数传递给ThreadPool.QueueUserWorkItem()方法就行了,传递的方法是依靠WaitCallBack代理对象,而线程的建立,管理和运行等工作都是由系统自动完成的,你无须考虑那些复杂的细节问题了。
我现在在之前的例子的基础上,使用线程池ThreadPool来实现。代码如下。
namespace ThreadDemo { class Program { static void Main(string[] args) { // 使用ThreadPool实现 Fish fish1 = new Fish { Name = "小黄鱼" }; Fish fish2 = new Fish { Name = "大鲨鱼" }; Fish fish3 = new Fish { Name = "灯笼鱼" }; Fish fish4 = new Fish { Name = "红鲤鱼" }; Fish fish5 = new Fish { Name = "灯笼鱼" }; ThreadPool.QueueUserWorkItem(f => { fish1.Move(); }); //lambda表达式 ThreadPool.QueueUserWorkItem(f => { fish2.Move(); }); ThreadPool.QueueUserWorkItem(f => { fish3.Move(); }); ThreadPool.QueueUserWorkItem(f => { fish4.Move(); }); ThreadPool.QueueUserWorkItem(f => { fish5.Move(); }); Console.ReadKey(); } } /// <summary> /// 鱼 /// </summary> public class Fish { public string Name { get; set; } public int Score { get; set; } public Fish() { } public void Move() { Console.WriteLine(string.Format("{0}在游来游去...", Name)); } } }
程序运行结果如下。
JS/tdXzvPK3tqKgoKA4UYqKigoLCz3PKyiHv1BQUJwqen+ddFq78OX0dt8/vf33z2j/gzM6/ODMDj88s8MPz+r4o7M6/ujsTj8+u9OPz+n0k3M6/+Tczj89t8tPz+vys/O6/uz8rj8/v+vPL+j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AuApzDrEUFhbCXwCApMDMQ4F5Cf4CACQF0Tz2An8BAJIF/AUAcBX4CwDgKvAXAMBVRPOYOsBfAIAkIuVf6lH4CwCQUNTnR/EQ/AUASC7a9a8C3Xut8BcAIFlg/R4A4CrwFwDAVeAvAICrwF8AAFdhwiECfwEAEkRhQKj+omR0vATtj4JCL+x3tDzsf3SHbS63QX+yIX4fqP7yaATtDwAd6akBWye2gX6yMfqLEi5ofxQUeuG/o+UJmJbY+m7FCuUnG+JXAv5CcaYg/3J0S//JBi1Z+auA8HdJKChRFeRfbm3FCiuqMcSfbKBfBulCgf3FvjIwjQP+Qom8IP9ydMuLVhrlwf3leV5RUZEYP5i/+Fee9t8wFJQIC/Ivt7ZihRVfb1AKk1d4f4mvbJjGAX+hRF6Qfzm65cWkDrq/RHmJ8ZF/oSS9IP9yaytWWMky//KUzCukv8qx/oWS84L8y9EtL9msf0nyymr9i4/G/huGghJhQf7l1lassBL6+0dVXhH4yzIO+Asl8oL8y9Et/SerLSZ5ifHhL5SkF+Rfbm3FCuUnqz1kkpd0IfgLJekF+ZejW/pPVioWeQV7fiwiE7Q/AHSQfzm0DeENuryK6P4CIDnU+LTElrgN8ZMNJC+Sv8oJ6R8KCgpK7ouPvzwAAEgwNn+hoKCgJL/AXygoKK6WE/wV/vshAACoCY77K6KviQAAIKd4nldQg0txAACQDf8PCSzMQwjh6gUAAAAASUVORK5CYII=" alt="" />
下一篇文章我将要总结.net 4.0中新增的特性Task任务,欢迎大家继续关注。