Applying the ThreadStatic Attribute

The ThreadStatic attribute can be applied to a shared field. Normally if a field is Shared, that field is accessible to an instance of the class as well as through the class itself.

The ThreadStatic attribute ensures that each instance of a class gets a unique copy of shared fields in those instances. Listing 14.7 demonstrates the ThreadStatic attribute.

Listing 14.7. Using the ThreadStatic attribute
						1:  Imports System.Threading
2:
						3:  Public Class ThreadStaticDemo
4:    <ThreadStatic()> Private Shared I As Integer = 0
5:    Private Count As Integer = 0
6:
						7:    Private Sub WriteCount()
8:
						9:      Console.WriteLine( _
10:       String.Format("Thread {0}  added {1}  to count", _
11: Thread.CurrentThread.GetDomain.GetCurrentThreadId(), ...

Get Visual Basic® .NET Unleashed 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.