远程缓存对象
我在单例远程处理对象 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 函数只是从数据库表中读取一行并将字段复制到一个小数据结构中。
问题
- 此代码多线程安全吗(在远程处理环境中)
- 不同的代码是否有任何性能优势
I'm using the following code in a singleton remoting object MBRO. This function is only called on the server side.
''' <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
The LoadRecord function simply reads a line from a database table and copies the fields into a little data structure.
The question
- Is this code multithreading safe (in a remoting environment)
- Are there any performance benefits for different code
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这取决于 dcLoader.LoadRecord 的作用。我猜测这只是读取一些数据并且不会更新任何状态,我还假设 dictDataCentricObject 的其他访问器锁定该对象。如果这是真的,那么我认为这段代码是线程安全的。
如果 dcLoader.LoadRecord 成本低廉,您可以在锁定之前执行此操作以提高并发性。但是,我怀疑它会导致对数据库的调用,因此为了整体性能,最好保持原样。这确实意味着对该函数的调用将在访问更昂贵的资源时进行序列化。当且仅当这会导致性能问题时,您可以在 dcLoader.LoadRecord 周围实现一些缓存。
It depends on what
dcLoader.LoadRecord
does. I'm going to take a guess that this just reads some data and does not update any state, I'm also assuming that other accesors ofdictDataCentricObject
lock on that object. If this is true then I think this code is thread-safe.If
dcLoader.LoadRecord
was inexpensive you could do it before your lock to improve concurrency. However, I suspect it results in a call to the database so for overall performance it may be better to stay where it is. This does mean that calls to the function will serialise on access to a more expensive resource. If, and only if, this causes you a performance problem you could implement some caching arounddcLoader.LoadRecord
.