O'Reilly logo

VB.NET Language in a Nutshell, Second Edition by Steven Roman PhD, Paul Lomax, Ron Petrusha

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Name

ThreadStatic Attribute

Class

System.ThreadStaticAttribute

Valid On

Field

Description

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.

Constructor

New(  )

Properties

None

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required