.net 添加后立即在字典中发现KeyNotFound异常
我们有一个基类,我们的大多数业务对象都继承自该基类。第一次访问任何子类时,我们运行call方法来缓存各种反射数据,以备将来使用。添加到这些集合的条目永远不会被删除。当我得到错误时(在With行),我可以看到类型被正确地添加到了_AllProperties字典(Count=22),但没有添加到_ImplementedIParent字典(Count=21) 错误是断断续续的。我已经追了几天了,不知道为什么会发生这样的事情。我在运行VS2019时检查了所有CLRE,在add上没有得到任何错误,但它不在下一行中 下面是基类中的相关代码.net 添加后立即在字典中发现KeyNotFound异常,.net,vb.net,.net,Vb.net,我们有一个基类,我们的大多数业务对象都继承自该基类。第一次访问任何子类时,我们运行call方法来缓存各种反射数据,以备将来使用。添加到这些集合的条目永远不会被删除。当我得到错误时(在With行),我可以看到类型被正确地添加到了_AllProperties字典(Count=22),但没有添加到_ImplementedIParent字典(Count=21) 错误是断断续续的。我已经追了几天了,不知道为什么会发生这样的事情。我在运行VS2019时检查了所有CLRE,在add上没有得到任何错误,但它不在
Public Class BaseClass
Private Shared ReadOnly _AllProperties As Concurrent.ConcurrentDictionary(Of Type, List(Of PropertyInfo)) = New Concurrent.ConcurrentDictionary(Of Type, List(Of PropertyInfo))
Private Shared ReadOnly _ImplementedIParent As Dictionary(Of Type, Dictionary(Of Type, BaseObjectParentDetail)) = New Dictionary(Of Type, Dictionary(Of Type, BaseObjectParentDetail))
Protected Shared Sub BuildPropertyList(CurrentType As Type)
Try
SyncLock CurrentType
If _AllProperties.ContainsKey(CurrentType) Then
Exit Sub
End If
_AllProperties.TryAdd(CurrentType, New List(Of PropertyInfo))
_ImplementedIParent.Add(CurrentType, New Dictionary(Of Type, BaseObjectParentDetail))
With _ImplementedIParent(CurrentType) '<-- Throws KeyNotFound exception here
'do stuff
End With
End SyncLock
Catch ex As Exception
'do error stuff
Throw
End Try
End Sub
End Class
如果_AllProperties.TryAdd(CurrentType,新列表(PropertyInfo)),则(…)
然后将_implementedParentDim outdict作为字典(类型,BaseObjectParentDetail)=如果.TryGetValue(CurrentType,outdict)则为空然后“do stuff end if end with end if
为什么必须添加对象,然后立即从字典访问它?只需创建一个变量,然后添加它?If _AllProperties.TryAdd()…
counts。不要忽略它。顺便说一句,您可以尝试不同步CurrentType:使用类型为Object
的字段。重要的是并发线程无法获取同一对象上的锁,因此它们需要排队访问字典。
Public Class Schedule
Inherits BaseClass
Shared Sub New()
BuildPropertyList(GetType(Schedule))
End Sub
End Class