一般只需要使用AsParallel进行自动产生线程自动计算,无须使用Partition分区机制。
而分区往往和Parallel.ForEach使用,对每一块自身数据都是很大的情况下很适合:
namespace Csharp
{
public class HeaveyWork
{
public static Random rd = new Random(DateTime.Now.GetHashCode());
public void Wait()
{
//长时间工作
Thread.Sleep(rd.Next(10,100));
}
}
public class Program
{
static void Main(string[] args)
{
HeaveyWork[]works = new HeaveyWork[100];
for (int i = 0; i < works.Length; i++)
{
works[i] = new HeaveyWork();
}
Stopwatch watch = new Stopwatch();
watch.Start();
Parallel.ForEach<HeaveyWork>(Partitioner.Create(works, true), (work) => work.Wait());
watch.Stop();
Console.WriteLine(watch.ElapsedMilliseconds);
}
}
}
If you think one reply solves your problem, please mark it as
An Answer, if you think someone's reply helps you, please mark it as a
Proposed Answer
Help by clicking:
Click here to donate your rice to the poor
Click to Donate
Click to feed Dogs & Cats
Found any spamming-senders? Please report at:
Spam Report