这段代码是线程安全的吗?或者这样说:
无论如何调用 GetIt() 并且 GetIt() 将向 2 个不同的线程返回相同的数字
Private Shared hitCount As Long = 1
Public Shared Function GetIt() As Long
Threading.Interlocked.Increment(hitCount)
DoSomethingQuick(hitCount)
Return hitCount
End Function
似乎有可能,那么我应该使用
Interlocked.Read()
还是将整个事情锁定在一个块中? 最佳答案
是的,有一种可能性:
Threading.Interlocked.Increment(hitCount)
Threading.Interlocked.Increment(hitCount)
Return hitCount
Return hitCount
在第 3 步和第 4 步中,hitCount 将是相同的值。
但修复很容易 Interlocked.Increment 返回递增的值,因此只需将代码更改为:
Private Shared hitCount As Long = 1L
Public Shared Function GetIt() As Long
Return Threading.Interlocked.Increment(hitCount)
End Function
编辑
或者现在根据您的编辑,您有一个不错的计时漏洞。无论如何,这就是你想要的:
Public Shared Function GetIt() As Long
Dim localHitCount As Long = Threading.Interlocked.Increment(hitCount)
Console.Writeline("Something, something....")
Return localHitCount
End Function
编辑
然后这样做(这正是迈克尔在下面建议的)
Private Shared hitCount As Long = 1L
Public Shared Function GetIt() As Long
Dim localHitCount As Long = Threading.Interlocked.Increment(hitCount)
DoSomethingQuick(localHitCount )
Return localHitCount
End Function
关于.net - 使用互锁,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2230874/