【发布时间】:2019-11-08 21:09:50
【问题描述】:
作业被不同的线程添加到HashSet 并引发此错误。有什么解决办法吗?
ConcurrentDictionary<myKey, HashSet<Job>> _dictKeyJob;
_dictKeyJob.AddOrUpdate(myKey, key =>
{
return new HashSet<Job>({ Job };
}, (key, hashJobs) =>
{
if (Job.Status == eStatus.Cancelled)
{
hashJobs.Remove(Job);
}
else
{
hashJobs.Add(Job);
}
return hashJobs;
});
例外:
System.IndexOutOfRangeException: Index was outside the bounds of the array.
at System.Collections.Generic.HashSet`1.SetCapacity(Int32 newSize, Boolean forceNewHashCodes)
at System.Collections.Generic.HashSet`1.AddIfNotPresent(T value)
at Raj.OPS.Common.Test.<>c__DisplayClass38_0.<SetOrAddKey>b__1(mKey key, HashSet`1 hashJobs) in
at System.Collections.Concurrent.ConcurrentDictionary`2.**AddOrUpdate**(TKey key, Func`2 addValueFactory, Func`3 updateValueFactory)
【问题讨论】:
-
你能显示添加到字典方法的代码吗?
-
如果您能提供minimal reproducible example,那就太好了。我的水晶球建议您将
HashSet存储为ConcurrentDictionary中的值。ConcurrentDictionary不会神奇地使HashSet线程安全。 -
stackoverflow.com/questions/4307131/… 可能是合适的副本。
-
刚刚添加了确切的代码。
标签: c# multithreading hashset concurrentdictionary