Simple comprehension
Thread: is a sequence of instructions, an individual object.
Threadpool: In the process of using thread, it is troublesome for a programmer to have a new thread for each sequence that wants to be concurrent, so there is a need to have a way to manage threads uniformly, so that the programmer does not have to focus on the application management of threads, so a series of wrappers are carried out on thread. With the ThreadPool. Using ThreadPool, add sequences that need to be concurrent into the thread pool, and the thread pool dynamically requests threads for concurrent sequences based on the idle behavior of threads in its thread list.
Task: Later, the programmer found that in the process of using threadpool there are still a lot of inconvenience, such as: (1) ThreadPool does not support the thread cancellation, completion, failure notification and other interactive operations; (2) ThreadPool does not support the sequencing of thread execution Then we'll continue to encapsulate the threadpool, so. NET Framework4.0 has TPL and task.
Thread
One of the important reasons for choosing thread is because of its thread.sleep () member because it has no equivalent in either task or ThreadPool. However, if you do not introduce too much unnecessary complexity, consider replacing sleep () with a timer.
For thread this point of knowledge, focus on synchronization, deadlock and race and other issues, the sense of the key point is the lock () and Waithandler understanding. Here, the following parameters are passed and obtained.
The following section focuses on the documentation for MSDN: Http://msdn.microsoft.com/en-us/library/wkays279.aspx
- Passing parameters to threads
Because the constructor of the thread needs to pass a delegate reference with no return type and no argument, the best approach is to encapsulate the method that needs to be passed to the thread in a class, and then define the parameters that need to be passed to the thread as fields of that class. For example, to call the following parameter function through a thread:
1 Public Double Calarea (double length,double width)2{3double area= length*width; 4 return Area ; 5 }
This can be done using the following methods:
1 Public classAreaclass2 {3 Public Doublewidth;4 Public Doublelength;5 Public DoubleArea ;6 Public voidCalarea ()7 {8area=width*length;9 }Ten } One A Public voidtestareacal () - { -Areaclass areacal=NewAreaclass (); theSystem.Threading.Thread thread1=NewSystem.Threading.Thread (Areacal.calarea); -Areacal.width=2; -Areacal.length=3; - Thread1.start (); +}
Note, however, that if you look at the value of Areacal.area immediately after executing Thread1.start (), it does not necessarily exist. The easy way to get a valid return is described below.
The simple approach is to use the BackgroundWorker class. Use the BackgroundWorker class to manage your threads and generate an event after the thread finishes executing, and then process the results in the corresponding event handler function.
1 classAreaClass22 {3 Public DoubleBase;4 Public DoubleHeight;5 Public DoubleCalcArea ()6 {7 //Calculate the area of a triangle.8 return 0.5* Base *Height;9 }Ten } One A PrivateSystem.ComponentModel.BackgroundWorker BackgroundWorker1 -=NewSystem.ComponentModel.BackgroundWorker (); - the Private voidTestArea2 () - { - Initializebackgroundworker (); - +AreaClass2 AreaObject2 =NewAreaClass2 (); -Areaobject2.base = -; +Areaobject2.height = +; A at //Start the asynchronous operation. - Backgroundworker1.runworkerasync (AREAOBJECT2); - } - - Private voidInitializebackgroundworker () - { in //Attach event handlers to the BackgroundWorker object. -Backgroundworker1.dowork + = to NewSystem.ComponentModel.DoWorkEventHandler (backgroundworker1_dowork); +backgroundworker1.runworkercompleted + = - NewSystem.ComponentModel.RunWorkerCompletedEventHandler (backgroundworker1_runworkercompleted); the } * $ Private voidBackgroundworker1_dowork (Panax Notoginseng Objectsender, - System.ComponentModel.DoWorkEventArgs e) the { +AreaClass2 AreaObject2 =(AREACLASS2) e.argument; A //Return The value through the Result property. theE.result =Areaobject2.calcarea (); + } - $ Private voidbackgroundworker1_runworkercompleted ( $ Objectsender, - System.ComponentModel.RunWorkerCompletedEventArgs e) - { the //Access The result through the result property. - DoubleArea = (Double) E.result;WuyiMessageBox.Show ("The area is :"+area.tostring ()); the}
ThreadPool
ThreadPool is a static class.
Management process:
Many program-generated threads have more than half time in hibernation until an event wakes them up, and another part of the thread is only periodically woken up to change state information. ThreadPool can increase your application's usage of threads by providing a system-managed thread for your application. The thread pool will have a line Cheng look at the wait operation in the thread pool queue, and when the thread in the threads sink completes its task, it will return to the queue waiting for the thread to be reused. If all threads in the thread pool are running, the new task is added to the wait queue. The reuse of threads reduces the program overhead of opening a new thread for each task.
Features:
Thread management inside ThreadPool is done by the class library (or the operating system), not by the application.
Threads inside the thread pool are all background threads (that is, their Isbackgroud property is true). This means that when all foreground threads have finished running, the thread pool threads do not keep the program running.
Thread pools are typically used on service applications. Each incoming request is assigned to each thread in the thread pool so that the individual requests can be processed asynchronously.
use:
The simple use of the thread pool can be done through the QueueUserWorkItem method. If you need to pass parameters to a task, you can pass a state object, and if you have multiple arguments to pass, encapsulate multiple parameters in the structure or the fields of the object. note, however, that once a method joins the thread queue, the execution of the method cannot be canceled :
Public Static void Main () {System.Threading.ThreadPool.QueueUserWorkItem (new System.Threading.WaitCallback ( Asyntask), asyndata); // Other code Snippets ... publicvoid asyntask (object State ) {//codes Need to executed asynchronously}
The size of the thread pool can be accessed or set through the GetMaxThreads or SetMaxThreads method, but notice that too large or too small will affect the performance of the program.
In addition, there are two ways to get the ThreadPool return value, see what the thread above says.
Task and TPL
The knowledge about task and TPL is also described later in detail. Here is a brief talk of the main features of the task.
- The task contains a ContinueWith () method that links the task as long as the first task in the chain completes, triggering other tasks that have been registered after it. There is also an interesting place where you can add multiple tasks with ContinueWith (), and all the tasks you add will start running in parallel after the pioneer task (parent Task) is finished. In addition, you can have a Taskcontinuationopitons enumeration value in the ContinueWith () statement, which, by specifying the value, determines whether to run subtasks based on the operation of the Pioneer task.
- Supports collaborative cancellation tasks. By using the System.Threading.CancellationToken. A thread requests a cancel task by setting the CancellationToken (struct type), and the running thread decides whether to continue running by checking the CancellationToken. Another area of concern is that threads terminated by CancellationToken will not cause the thread's faulted property to be true if there is no damage in some way.
1 Public Static voidMain ()2 {3CancellationTokenSource cancellationtokensource=NewCancellationTokenSource ();4Task task. Task.Factory.StartNew (() =loopwork (Cancellationtokensource.token), cancellationtokensource.token);5Thread.Sleep ( +);6 Cancellationtokensource.cancel ();7 task.wait ();8 }9 Ten Private Static voidloopwork (CancellationToken cancellationtoken) One { A while(!cancellationtoken.iscancellationrequested) - { - //Work need to being done the } -}
The task also supports the IDisposable method, which is required to support the Wait () feature.
Parallel iterations
When using a For loop iteration, the processor iterates sequentially. But if each iteration does not affect each other, and if the system has multiple processors, we can make each processor responsible for one iteration, thus increasing efficiency.
Related classes: System.Threading.Tasks.Parallel.
Related methods: Parallel.For () and Parallel.ForEach ()
Note Three: The computer has multiple processors, the order of parallel iterations is not fixed, and when used, it is necessary to consider the non-atomicity of the internal code of the iteration to bring about the problem of race.
1 //turn 10,000 lowercase words into uppercase2 Static voidMain ()3 {4 intiterations=10000;5 string[] word=New string[iterations];6 //here to initialize Word, enter 10,000 lowercase words7Parallel.For (0, iterations, (i) = =8 {9word[i]=Word[i].toupper ();Ten }); One}
[Multithreading]thread,threadpool,task and TPL knowledge Point finishing