ClassSystem.ThreadStaticAttribute Applies ToField ConstructorNew( ) PropertiesNone defined DescriptionThe <ThreadStatic> attribute specifies that the value of a static field is not shared across threads, so that each thread in the application has its own version of the field. In the absence of this attribute, a static field is shared across all threads. ExampleThe example illustrates the use of the <ThreadStatic> attribute by creating a second thread and having both threads increment a static field. With the <ThreadStatic> attribute, the variable's value is maintained on a per-thread basis. If you remove the <ThreadStatic> attribute and recompile the source, the variable is maintained on a per-application basis. Option Strict On Imports Microsoft.VisualBasic Imports System Imports System.Threading Public Class ThreadingTest <ThreadStatic> Private Shared keepCount As Integer Public Shared Sub Main( ) ' ----- Start the second thread. Dim otherThread As New Thread(AddressOf SecondThread) otherThread.Start ' ----- Do the primary thread's work. IncrementCount("T1,1:") DelayLoop(2000) IncrementCount("T1,2:") DelayLoop(2000) IncrementCount("T1,3:") End Sub Private Shared Sub SecondThread( ) ' ----- Do the second thread's work. IncrementCount("T2,1:") DelayLoop(2000) IncrementCount("T2,2:") DelayLoop(2000) IncrementCount("T2,3:") End Sub Private Shared Sub IncrementCount(ByVal statusText As String) ' ----- Increment the thread-specfic static counter. keepCount += 1 Console.WriteLine(statusText & keepCount) End Sub Private Shared Sub DelayLoop(ByVal milliSecs As Integer) ' ----- Wait a while. System.Threading.Thread.Sleep(milliSecs) End Sub End Class |