gpt4 book ai didi

.net - Monitor.TryEnter 建议

转载 作者:行者123 更新时间:2023-12-04 16:22:20 25 4
gpt4 key购买 nike

我们在 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.exit,即使 monitor.tryenter 为 false。

最佳答案

错误是从 Monitor.Exit 调用中抛出的。发生的情况是 TryEnter 偶尔会超时并且未获取锁,但是 Monitor.Exit 总是被调用,因为它是 finally block 。那就是问题所在。这是修复它的方法。

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 Try

关于.net - Monitor.TryEnter 建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3368820/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com