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

Get VB.NET Language in a Nutshell, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.