Because the project response is too slow, the code optimization space is not small, in the case of temporarily unable to adjust the system architecture, only use. The TPL in the net solves some of the problem that some modules take too much time. But in the use of the process also encountered some problems, now write it down for memo.
1. Use of Parallel.ForEach
1 Static voidMain (string[] args)2 {3 //Test ();4 Testparllel ();5 console.readline ();6 }7 8 Private Static voidTestparllel ()9 {Ten varList =Newlist<int> (6000); One A for(inti =0; I <6000; i++) - { - list. ADD (i); the } -Parallel.ForEach (list, (p, state) = ={Invoke (P);}); - } - + Static voidInvoke (inti) - { + Console.WriteLine (Thread.CurrentThread.ManagedThreadId); AThread.Sleep (30000); at}View Code
If the maximum number of threads is not set:
A> to set the maximum thread, the TPL default thread count is the number of tasks (if the system allows, setting threadpool.setmaxthreads has no effect).
B> TPL starts 5 threads by default and the number of tasks is less than 5, starting several threads of the task.
C> If there are more tasks, TPL adds threads every 100 milliseconds after initializing 5 threads until the maximum number of threads is reached. If a task is completed during a new thread, no new threads will be added.
Disadvantage: The number of threads can not be controlled, it is easy to cause high CPU, the system loses response.
When the maximum number of threads is set:
1 Private Static voidTestparllel ()2 {3 varList =Newlist<int> (6000);4 5 for(inti =0; I <6000; i++)6 {7 list. ADD (i);8 }9Parallel.ForEach (list,Newparalleloptions {maxdegreeofparallelism =2}, (P, state) = ={Invoke (P);});Ten}View Code
Set the maximum number of threads to 2
The a> system operates in a controlled state and does not cause high CPU conditions.
. NET parallel Parallel use