我在单例远程处理对象MBRO中使用以下代码。此功能仅在服务器端调用。
''' <summary>
''' Return a cached DataCentricObject
''' </summary>
''' <created_by>CodingBarfield</created_by>
''' <date>04-08-2011</date>
Function DataCentricObjectName(ByVal intID As Integer) As String
Try
SyncLock dictDataCentricObject
If Not dictDataCentricObject.ContainsKey(intID) Then
Dim st As struct = dcLoader.LoadRecord(intID)
dictDataCentricObject(intID) = st.Descript
End If
Return dictDataCentricObject(intID)
End SyncLock
Catch ex As Exception
Throw New Exception("Error in GetTargName", ex)
End Try
End Function
Private dictDataCentricObject As New Dictionary(Of Integer, String)
Dim dcLoader As New DataCentricObject
LoadRecord函数只是从数据库表中读取一行,并将字段复制到一个小数据结构中。
问题
答案 0 :(得分:1)
这取决于dcLoader.LoadRecord
的作用。我将猜测这只是读取一些数据并且不更新任何状态,我还假设dictDataCentricObject
的其他加速器锁定该对象。如果这是真的那么我认为这段代码是线程安全的。
如果dcLoader.LoadRecord
价格便宜,您可以在锁定之前执行此操作以提高并发性。但是,我怀疑它会导致对数据库的调用,因此对于整体性能而言,保持原状可能会更好。这意味着对函数的调用将序列化访问更昂贵的资源。如果且仅当这会导致性能问题时,您可以围绕dcLoader.LoadRecord
实现一些缓存。