.net的并行库,存在于.net4.0中,是一套用于并行处理多任务的库。以下是代码实例,这里只用并行库中一个简单的类而已,大家可深入研究,但测试发现,并行库的运行速度比普通的循环要慢。我是从csdn的金老师,那里学的,所以部分代码相似,特此声明。
Code
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Web;
5using System.Web.UI;
6using System.Web.UI.WebControls;
7using System.Diagnostics;
8using System.Threading;
9
10namespace WebApplication3
11{
12 public partial class _Default : System.Web.UI.Page
13 {
14 protected void Page_Load(object sender, EventArgs e)
15 {
16 this.TestParaller();
17 }
18
19 private void TestParaller()
20 {
21
22 Stopwatch sw = new Stopwatch();
23 sw.Start();
24 Parallel.For(0, 100, (i) => SumI(i));
25 sw.Stop();
26 Response.Write(sw.ElapsedMilliseconds.ToString() + "parallel ");
27 sw.Reset();
28
29 sw.Start();
30 for (int i = 0; i < 100; i++)
31 {
32 SumI(i);
33 }
34 sw.Stop();
35 Response.Write(sw.ElapsedMilliseconds.ToString());
36 }
37
38 private void SumI(int i)
39 {
40 i = i + 1;
41 }
42
43 }
44}
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Web;
5using System.Web.UI;
6using System.Web.UI.WebControls;
7using System.Diagnostics;
8using System.Threading;
9
10namespace WebApplication3
11{
12 public partial class _Default : System.Web.UI.Page
13 {
14 protected void Page_Load(object sender, EventArgs e)
15 {
16 this.TestParaller();
17 }
18
19 private void TestParaller()
20 {
21
22 Stopwatch sw = new Stopwatch();
23 sw.Start();
24 Parallel.For(0, 100, (i) => SumI(i));
25 sw.Stop();
26 Response.Write(sw.ElapsedMilliseconds.ToString() + "parallel ");
27 sw.Reset();
28
29 sw.Start();
30 for (int i = 0; i < 100; i++)
31 {
32 SumI(i);
33 }
34 sw.Stop();
35 Response.Write(sw.ElapsedMilliseconds.ToString());
36 }
37
38 private void SumI(int i)
39 {
40 i = i + 1;
41 }
42
43 }
44}