我正在 c# 4、.NET 4.0 中测试一些并行化解决方案。
我有一些奇怪的结果,所以我想知道我是否以正确的方式做事。
这是我的代码的描述:
//This will count the number of times we pass in the loop
private static double count_method_5 = 0;
//This will generate a MD5 hash
private static void GenerateMD5Hash(double i)
{
var md5M = MD5.Create();
byte[] data = Encoding.Unicode.GetBytes(Environment.UserName + i.ToString());
byte[] result = md5M.ComputeHash(data);
}
static void Main(string[] args)
{
//Launch method Parallel for method 2
var time9 = watch.ElapsedMilliseconds;
int loop2 = 0;
int limit2 = 300000;
Parallel.For(loop2, limit2, new ParallelOptions { MaxDegreeOfParallelism = 8 }, i =>
{
GenerateMD5Hash(i);
count_method_5++;
loop2++;
});
var time10 = watch.ElapsedMilliseconds;
Console.WriteLine("Parallel For second method (method 5) Elapsed time :" + (time10 - time9) + "ms");
Console.WriteLine("Count method 5 : " + count_method_5);
}
这段代码给了我这个结果:
计数方法5:299250
而不是300000
.
这是并行性的错误吗?