我们在vb.net应用程序的一部分中使用并行扩展来从字典(字符串、数据表)中检索数据表。在检索表的方法中,我们使用Monitor.TryEnter。有时,我们会收到错误消息“对象同步方法是从未同步的代码块中调用的”。下面是我们的方法:
Try
if Monitor.TryEnter(_ProductCollection, 200) = true then
_ProductCollection.TryGetValue(name, ReturnValue)
end if
Finally
Monitor.Exit(_ProductCollection)
End Try在尝试退出之前,我是否应该尝试实现一个循环,以确保我们获得了锁?我认为抛出这个错误是因为即使monitor.tryenter为false,我也要尝试执行monitor.exit。
发布于 2010-07-30 21:44:25
该错误是从Monitor.Exit调用引发的。发生的情况是,TryEnter偶尔会超时,锁不会被获取,但Monitor.Exit始终会被调用,因为它是finally块。这就是问题所在。下面是如何修复它的方法。
Dim acquired As Boolean = False
Try
acquired = Monitor.TryEnter(_ProductionCollection, 200)
If acquired Then
' Do your stuff here.
End If
Finally
If acquired Then
Monitor.Exit(_ProductionCollection)
End If
End Tryhttps://stackoverflow.com/questions/3368820
复制相似问题