我对多线程中代码的准确性感到困惑,因为有些时候我得到了错误的结果。
看起来可能会失败。下面是代码。
public class MyKeyValue
{
public double Key { get; set; }
public double Value { get; set; }
}
public class CollMyKeyValue : List<MyKeyValue>
{
public void SumUpValues(CollMyKeyValue collection)
{
int count =0;
Parallel.For(count, this.Count,
(i) =>
{
this[count].Value = this[count].Value + collection[count].Value;
Interlocked.Increment(ref count);
});
}
}
假设两个集合中的键相同。
我想将一个集合的值添加到另一个集合中。它安全吗?
我尚未将
this[count].Value = this[count].Value + collection[count].Value;放在线程安全块中。
请您参考如下方法:
只需删除互锁的增量:
public void SumUpValues(CollMyKeyValue collection)
{
//int count =0;
Parallel.For(0, this.Count,
(i) =>
{
this[i].Value = this[i].Value + collection[i].Value;
//Interlocked.Increment(ref count);
});
}
您的版本正在循环内更改index变量。
For循环自动执行此操作;在并行版本中,每个线程都需要一个
i(或
i集)来执行,因此在循环中进行递增是没有意义的。
