Parallel.ForEach , ThreadPool.QueueUserWorkItem

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading;
 6 using System.Threading.Tasks;
 7 
 8 namespace ParallelThreadPool
 9 {
10     class Program
11     {
12         static void Main(string[] args)
13         {
14             List<int> list = InitialList(100);
15             Console.WriteLine("ParallelList开始");
16             ParallelList(list);
17             Console.WriteLine("ThreadPoolList开始");
18             ThreadPoolList(list);
19             Console.ReadKey();
20         }
21 
22         /// <summary>
23         /// 初始化队列
24         /// </summary>
25         /// <param name="length"></param>
26         /// <returns></returns>
27         private static List<int> InitialList(int length)
28         {
29             List<int> list = new List<int>();
30             for (int i = 0; i < length; i++)
31             {
32                 list.Add(i);
33             }
34             return list;
35         }
36 
37         /// <summary>
38         /// Paralle循环
39         /// </summary>
40         /// <param name="list"></param>
41         private static void ParallelList(List<int> list)
42         {
43             Parallel.ForEach(list, (item) =>
44             {
45                 Console.WriteLine(string.Format("Paralle循环,元素{0}", item));
46             });
47             Console.WriteLine("-----------------------------------Paralle----------------------------------");
48         }
49 
50         /// <summary>
51         /// ThreadPool循环
52         /// </summary>
53         /// <param name="list"></param>
54         private static void ThreadPoolList(List<int> list)
55         {
56             ThreadPool.QueueUserWorkItem(new WaitCallback(delegate
57             {
58                 foreach (var item in list)
59                 {
60                     Console.WriteLine(string.Format("ThreadPool循环,元素{0}", item));
61                 }
62             }));
63             Console.WriteLine("-----------------------------------ThreadPool----------------------------------");
64         }
65     }
66 }

Parallel.ForEach:执行foreach操作,其中可能会并行迭代。

ThreadPool.QueueUserWorkItem:将方法排入队列以便执行。 此方法在有线程池线程变得可用时执行。

仅作为自己记录一下,验证猜想:

Parallel.ForEach不异步,并行迭代,执行顺序会乱。

ThreadPool.QueueUserWorkItem 开线程,异步不影响后面代码执行,按照队列顺序一个个执行。

posted @ 2014-11-26 16:28  一杯晨光  阅读(840)  评论(0编辑  收藏  举报