现代的计算机以前不像以前的计算机了,所以,我们的代码也需要优化了,如果仍然按照旧的处理方式,就不能将用户的计算机性能发挥出来,这也是提升用户体验的一种方式!
Parallel 是C#4.0 提供一种并行的处理方式,如果你的的For循环是可以并行的且涉及大量的工作,那么请用Parallel的For替换你的for循环吧,这会大大提升程序的效率
先贴代码吧:
static int[] _Data;
static Stopwatch _Sw = new Stopwatch();
static void Main(string[] args)
{
//prepare data
_Data = new int[10];
for (int i = 0; i < _Data.Length; i++)
_Data[i] = i;
_Sw.Start();
NewMethod();
_Sw.Stop();
Console.WriteLine("new use time :{0}", _Sw.ElapsedMilliseconds);
_Sw.Restart();
OldMethod();
Console.WriteLine("old use time :{0}", _Sw.ElapsedMilliseconds);
Console.ReadKey();
}
static void NewMethod()
{
Parallel.For(0, _Data.Length, DoMethod);
}
static void OldMethod()
{
for (int i = 0; i < _Data.Length; i++)
DoMethod(i);
}
static void DoMethod(int i)
{
//输出当前的i 并模拟耗时操作
Console.WriteLine("Do:{0}", i);
Thread.Sleep(500);
}
Parallel.For是自动创建了多个线程,并行的执行DoMethod,所以每次执行都是无序的,如果你的的For循环是可以并行的且涉及大量的工作,,那么用Parallel吧,可以看到cpu利用率猛的飙了上去哦
ps:线程是昂贵的,如果是简单的循环,使用for循环吧,因为创建并行任务和执行上下文切换的时间将超过使用并行节省的时间。