In the previous article, we summarized the most basic Thread knowledge point of multithreading and learned how to start a new asynchronous Thread to do something. But when we want to enable multithreading, if we still use the Thread, we need to manage the startup, suspension, and termination of each Thread, which is obviously very troublesome. Fortunately, the. net framework provides a thread pool ThreadPool to help us manage these threads, So we no longer need to manually terminate these threads. In this article, let's take a look at the thread pool ThreadPool. I would like to summarize it from the following aspects.
ThreadPool
The ThreadPool class is a static class and you cannot or do not need to generate its objects. Once a project is added to the thread pool using this method, the project cannot be canceled. Here you don't need to create a thread by yourself. We just need to write the job to be done as a function and pass it to ThreadPool as a parameter. the QueueUserWorkItem () method is enough. The passed method relies on the WaitCallBack proxy object, and the creation, management, and running of threads are automatically completed by the system, you don't have to worry about complicated details.
ThreadPool usage
I am using the ThreadPool of the thread pool based on the previous example. The Code is as follows.
Namespace ThreadDemo {class Program {static void Main (string [] args) {// use ThreadPool to implement Fish fish1 = new Fish {Name = "yellow croaker "}; fish fish2 = new Fish {Name = "Sharks"}; Fish fish3 = new Fish {Name = "Cage Fish"}; Fish fish4 = new Fish {Name = "red carp "}; fish fish5 = new Fish {Name = "lantern Fish"}; ThreadPool. queueUserWorkItem (f =>{ fish1.Move () ;}); // lambda expression ThreadPool. queueUserWorkItem (f =>{ fish2.Move () ;}); ThreadPool. queueUserWorkItem (f =>{ fish3.Move () ;}); ThreadPool. queueUserWorkItem (f =>{ fish4.Move () ;}); ThreadPool. queueUserWorkItem (f =>{ fish5.Move () ;}); Console. readKey () ;}//< summary> /// Fish // </summary> public class Fish {public string Name {get; set ;} public int Score {get; set;} public Fish () {} public void Move () {Console. writeLine (string. format ("{0} on a tour... ", Name ));}}}
The program running result is as follows.
In the next article, I will summarize the new feature Task in. net 4.0.