本文整理汇总了VB.NET中System.Threading.Interlocked类的典型用法代码示例。如果您正苦于以下问题:VB.NET Interlocked类的具体用法?VB.NET Interlocked怎么用?VB.NET Interlocked使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Interlocked类的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的VB.NET代码示例。
示例1: Main
' 导入命名空间
Imports System.Threading
Namespace InterlockedExchange_Example
Class MyInterlockedExchangeExampleClass
'0 for false, 1 for true.
Private Shared usingResource As Integer = 0
Private Const numThreadIterations As Integer = 5
Private Const numThreads As Integer = 10
<MTAThread> _
Shared Sub Main()
Dim myThread As Thread
Dim rnd As New Random()
Dim i As Integer
For i = 0 To numThreads - 1
myThread = New Thread(AddressOf MyThreadProc)
myThread.Name = String.Format("Thread{0}", i + 1)
'Wait a random amount of time before starting next thread.
Thread.Sleep(rnd.Next(0, 1000))
myThread.Start()
Next i
End Sub
Private Shared Sub MyThreadProc()
Dim i As Integer
For i = 0 To numThreadIterations - 1
UseResource()
'Wait 1 second before next attempt.
Thread.Sleep(1000)
Next i
End Sub
'A simple method that denies reentrancy.
Shared Function UseResource() As Boolean
'0 indicates that the method is not in use.
If 0 = Interlocked.Exchange(usingResource, 1) Then
Console.WriteLine("{0} acquired the lock", Thread.CurrentThread.Name)
'Code to access a resource that is not thread safe would go here.
'Simulate some work
Thread.Sleep(500)
Console.WriteLine("{0} exiting lock", Thread.CurrentThread.Name)
'Release the lock
Interlocked.Exchange(usingResource, 0)
Return True
Else
Console.WriteLine(" {0} was denied the lock", Thread.CurrentThread.Name)
Return False
End If
End Function
End Class
End Namespace
开发者ID:VB.NET开发者,项目名称:System.Threading,代码行数:59,代码来源:Interlocked
注:本文中的System.Threading.Interlocked类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论