ThreadStatic Attribute


ThreadStatic Attribute

Class

System.ThreadStaticAttribute

Applies To

Field

Constructor

     New(  ) 

Properties

None defined

Description

The <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.

Example

The 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 




Visual Basic 2005(c) In a Nutshell
Visual Basic 2005 in a Nutshell (In a Nutshell (OReilly))
ISBN: 059610152X
EAN: 2147483647
Year: 2004
Pages: 712

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net