C# 4.0支持并行任务,并行任务能提高CPU的利用率(尤其是当前CPU基本都是多核情况下),缩短处理时间,代码取自:
http://www.dotnetjalps.com/2012/12/Parallel-task-with-task-parallel-library-in-Csharp.html
http://www.dotnetjalps.com/2012/12/Parallel-task-with-task-parallel-library-in-Csharp.html
http://www.cnblogs.com/luminji/archive/2011/05/19/2050692.html
普通的非并行任务
using System;
02 using System.Threading;
03 using System.Diagnostics;
04
05 namespace ParrallelTask
06 {
07 class Program
08 {
09 static void Main(string[] args)
10 {
11 Stopwatch stopWatch = new Stopwatch();
12 stopWatch.Start();
13 DoSomeWork();
14 DoSomework2();
15 stopWatch.Stop();
16 Console.WriteLine("Time consumed: {0}", stopWatch.Elapsed);
17 }
18
19 public static void DoSomeWork()
20 {
21 Thread.Sleep(1000);
22 Console.WriteLine("Work completed");
23 }
24 public static void DoSomework2()
25 {
26 Thread.Sleep(1000);
27 Console.WriteLine("Work completed2");
28 }
29
30 }
31 }
改写后的并行任务
using System;
02 using System.Threading;
03 using System.Diagnostics;
04 using System.Threading.Tasks;
05
06
07 namespace ParrallelTask
08 {
09 class Program
10 {
11 static void Main(string[] args)
12 {
13 Stopwatch stopWatch = new Stopwatch();
14 stopWatch.Start();
15 Parallel.Invoke(
16 new Action(DoSomeWork),
17 new Action(DoSomework2)
18 );
19 stopWatch.Stop();
20 Console.WriteLine("Time consumed: {0}", stopWatch.Elapsed);
21 }
22
23 public static void DoSomeWork()
24 {
25 Thread.Sleep(1000);
26 Console.WriteLine("Work completed");
27 }
28 public static void DoSomework2()
29 {
30 Thread.Sleep(1000);
31 Console.WriteLine("Work completed2");
32 }
33
34 }
35 }
针对集合元素的并行处理
List<int> nums = new List<int> { 1, 2, 3, 4 };
2 Parallel.ForEach(nums, (item) =>
3 {
4 Console.WriteLine("针对集合元素{0}的一些工作代码……", item);
5 });
[C#]代码
01 static void Main(string[] args)
02 {
03 Parallel.Invoke(
04 () =>
05 {
06 Console.WriteLine("任务1……");
07 },
08 () =>
09 {
10 Console.WriteLine("任务2……");
11 });
12 Console.ReadKey();
13 }