April 2002
Intermediate to advanced
688 pages
19h 51m
English
ThreadStatic Attribute
System.ThreadStaticAttribute
Field
Specifies that the value of a static field is
not shared across threads (that is, each thread in the application
has its own value). In the absence of the
<ThreadStatic> attribute, a static field is
shared across threads.
New( )
None
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, you would find that it is
maintained on a per application basis.
Option Strict On Imports Microsoft.VisualBasic Imports System Imports System.Threading Public Class CMain <ThreadStatic> Private Shared lCount As Integer Public Shared Sub Main Dim oThread As New Thread(AddressOf Thread2Proc) oThread.Start Console.WriteLine("First call to CallCount") CallCount( ) DelayLoop(2000) Console.WriteLine("Second call to CallCount") CallCount( ) DelayLoop(2000) Console.WriteLine("Third call to CallCount") CallCount( ) End Sub Private Shared Sub CallCount( ) lCount += 1 Console.WriteLine(lCount) End Sub Private Shared Sub DelayLoop(millisecs As Integer) Dim oThread As Thread oThread = Thread.CurrentThread oThread.Sleep(millisecs) End Sub Private Shared Sub Thread2Proc Console.WriteLine("2nd thread call 1 to CallCount") CallCount( ) DelayLoop(2000) Console.WriteLine("2nd ...Read now
Unlock full access