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 attribute1: 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(), _ 12: Count)) 13: 14: End Sub 15: 16: Public Sub Increment() 17: 18: While (Interlocked.Increment(I) < 1000000) 19: Count += 1 20: End While 21: 22: WriteCount() 23: 24: End Sub 25: 26: Public Shared Function Instance() As ThreadStaticDemo 27: Return New ThreadStaticDemo() 28: End Function 29: 30: End Class 31: 32: 33: Module Module1 34: 35: 36: Sub Main() 37: 38: Dim Threads(10) As Thread 39: Dim I As Integer 40: For I = 0 To Threads.Length - 1 41: Threads(I) = New Thread(_ 42: AddressOf ThreadStaticDemo.Instance.Increment) 43: 44: Threads(I).IsBackground = True 45: Threads(I).Start() 46: Next 47: 48: For I = 0 To Threads.Length - 1 49: Threads(I).Join() 50: Next 51: 52: Console.ReadLine() 53: 54: End Sub 55: 56: End Module Listing 14.7 defines a class ThreadStaticDemo and a module Module1. Module1.Main creates 11 Thread objects, and each one increments a shared variable I some number of times until I is equal to one million. Notice the use of the ThreadStatic attribute on line 4. Line 4 as it is in the listing ensures that each instance of ThreadStaticDemo works with its own unique copy of I. With the ThreadStatic attribute, each thread increments its own I as reported by the WriteCount procedure. Remove the ThreadStatic attribute, and each thread works with the same I, and each thread performs only part of the total work. (See Figures 14.5 and 14.6.) Figure 14.5. The results from Listing 14.7 without the ThreadStatic attribute.
Figure 14.6. The results from Listing 14.7 with the ThreadStatic attribute.
Figure 14.5 shows the output from the console application without the ThreadStatic attribute where the workload is somewhat distributed, and Figure 14.6 shows the output from the example with the ThreadStatic attribute where each thread performs the same amount of work. |
Team-Fly |
Top |