VB.Net Tutorial/Thread/ThreadStatic — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
(нет различий)
|
Текущая версия на 15:56, 26 мая 2010
ThreadStatic
<source lang="vbnet">Imports System.Threading public class Test
Shared Dim obj As MyClass1 = new MyClass1 public Shared Sub Main Dim thread1 As New Thread(AddressOf doSomething) Dim thread2 As New Thread(AddressOf doSomething) Dim thread3 As New Thread(AddressOf doSomething) thread1.Start() thread2.Start() thread3.Start() End Sub Private Shared Sub doSomething() Dim i As Integer For i = 1 To 3 obj.SharedData = i obj.threadUniqueID = AppDomain.GetCurrentThreadId() Console.WriteLine("ID: " & obj.threadUniqueID & ", I:=" & i & ", SharedData: " & obj.SharedData.ToString()) Thread.CurrentThread.Sleep(250) Next End Sub
End class Public Class MyClass1
<ThreadStatic()> Public threadUniqueID As Integer Public SharedData As Integer = 0
End Class</source>
ID: 2564, I:=1, SharedData: 1 ID: 3196, I:=1, SharedData: 1 ID: 2656, I:=1, SharedData: 1 ID: 2564, I:=2, SharedData: 2 ID: 3196, I:=2, SharedData: 2 ID: 2656, I:=2, SharedData: 2 ID: 2564, I:=3, SharedData: 3 ID: 3196, I:=3, SharedData: 3 ID: 2656, I:=3, SharedData: 3
ThreadStatic field
<source lang="vbnet">Imports System.Threading Public Class SharedByThread
<ThreadStatic> Private Shared Count As Integer Public Shared Sub Main() Dim secondThread As New thread(AddressOf Thread2Proc) secondThread.Start() count = 100 For ctr As Integer = 0 to 10 Console.WriteLine("The value of count in the main thread is {0}.", count) IncrementCounter(200) Next End Sub Public Shared Sub Thread2Proc() count = 0 For ctr As Integer = 0 to 10 Console.WriteLine("The value of count in the second thread is {0}.", count) IncrementCounter(250) Next End Sub Public Shared Sub IncrementCounter(delay As Integer) count +=1 Thread.Sleep(delay) End Sub
End Class</source>
The value of count in the second thread is 0. The value of count in the main thread is 100. The value of count in the main thread is 101. The value of count in the second thread is 1. The value of count in the main thread is 102. The value of count in the second thread is 2. The value of count in the main thread is 103. The value of count in the second thread is 3. The value of count in the main thread is 104. The value of count in the second thread is 4. The value of count in the main thread is 105. The value of count in the main thread is 106. The value of count in the second thread is 5. The value of count in the main thread is 107. The value of count in the second thread is 6. The value of count in the main thread is 108. The value of count in the second thread is 7. The value of count in the main thread is 109. The value of count in the second thread is 8. The value of count in the main thread is 110. The value of count in the second thread is 9. The value of count in the second thread is 10.