是的,有一种可能:
- 线程 1 运行
Threading.Interlocked.Increment(hitCount)
- 线程 2 运行
Threading.Interlocked.Increment(hitCount)
- 线程 1 运行
Return hitCount
- 线程 2 运行
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