我创建了一个应用程序,该应用程序使用来自this包的Windows-API-Code-Pack从文件中读取属性。检索属性时出现问题
var width = fileInfo.Properties.GetProperty(SystemProperties.System.Video.FrameWidth).ValueAsObject;
代码在这里中断给我
System.ArgumentException: An item with the same key has already been added.
at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
at Microsoft.WindowsAPICodePack.Shell.PropertySystem.ShellPropertyFactory.GenericCreateShellProperty[T](PropertyKey propKey, T thirdArg)
at Microsoft.WindowsAPICodePack.Shell.PropertySystem.ShellProperties.GetProperty(PropertyKey key)
通常在PLINQ中调用这部分代码时会发生
.AsParallel().WithDegreeOfParallelism(_maxConcurrentThreads).ForAll(...)
即使将学位设置为1。我该如何解决?
答案 0 :(得分:1)
要扩展您现有的答案,将Dictionary切换为ConcurrentDictionary也可以解决问题并消除对锁的需求。
private static ConcurrentDictionary<int, Func<PropertyKey, ShellPropertyDescription, object, IShellProperty>> _storeCache
= new ConcurrentDictionary<int, Func<PropertyKey, ShellPropertyDescription, object, IShellProperty>>();
...
private static IShellProperty GenericCreateShellProperty<T>(PropertyKey propKey, T thirdArg)
{
...
Func<PropertyKey, ShellPropertyDescription, object, IShellProperty> ctor;
ctor = _storeCache.GetOrAdd((hash, (key, args) -> {
Type[] argTypes = { typeof(PropertyKey), typeof(ShellPropertyDescription), args.thirdType };
return ExpressConstructor(args.type, argTypes);
}, {thirdType, type});
return ctor(propKey, propDesc, thirdArg);
}
答案 1 :(得分:0)
遵循stuartd的建议,我可以通过修改包的源代码并在第this code行的第57和62行添加锁来解决此问题,就像这样
lock (_storeCache)
{
if (!_storeCache.TryGetValue(hash, out ctor))
{
Type[] argTypes = { typeof(PropertyKey), typeof(ShellPropertyDescription), thirdType };
ctor = ExpressConstructor(type, argTypes);
lock (_storeCache)
_storeCache.Add(hash, ctor);
}
}