Parallel.Invoke能并发运行多个方法。
Parallel.Invoke
精选 转载签名如下:
public static void Invoke(
params Action[] actions
)
是一个静态方法,无需实例化。参数是一个Action委托数组,可以填写任意多个方法,然后等他们运行完毕。方法无序执行。有4个逻辑内核也不是保证4个方法同时进行。
class Program
{
static void Main(string[] args)
{
var sw = Stopwatch.StartNew();
//sequential
Console.WriteLine("sequential");
Sum1();
Sum2();
Console.WriteLine(sw.Elapsed.ToString());
//parallel
sw = Stopwatch.StartNew();
Console.WriteLine("parallel");
Parallel.Invoke(Sum1, Sum2);
Console.WriteLine(sw.Elapsed.ToString());
}
static void Sum1()
{
long sum = 0;
for (int i = 0; i < 10000000; i++)
{
sum += i;
}
Console.WriteLine(sum.ToString());
}
static void Sum2()
{
long sum = 0;
for (int i = 0; i < 10000000; i++)
{
sum -= i;
}
Console.WriteLine(sum.ToString());
}
}
sequential
49999995000000
-49999995000000
00:00:00.0861083
parallel
49999995000000
-49999995000000
00:00:00.0458769
Press any key to continue . . .
从上断程序看出,并行运行节省了约一半的CPU时间
但是当两个函数都耗时不多的情况下,并行运行反而慢了。看下面的代码
static void Main(string[] args)
{
var sw = Stopwatch.StartNew();
//sequential
Console.WriteLine("sequential");
Sum1();
Sum2();
Console.WriteLine(sw.Elapsed.ToString());
//parallel
sw = Stopwatch.StartNew();
Console.WriteLine("parallel");
Parallel.Invoke(Sum1, Sum2);
Console.WriteLine(sw.Elapsed.ToString());
}
static void Sum1()
{
long sum = 0;
for (int i = 0; i < 100; i++)
{
sum += i;
}
Console.WriteLine(sum.ToString());
}
static void Sum2()
{
long sum = 0;
for (int i = 0; i < 100; i++)
{
sum -= i;
}
Console.WriteLine(sum.ToString());
}
sequential
4950
-4950
00:00:00.0013660
parallel
4950
-4950
00:00:00.0015971
Press any key to continue . . .
下一篇:Parallel.For
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
Parallel.For与Parallel.ForEachc# 线程 JAVA