Option Explicit
Option Strict
Imports System
Imports System.Threading
Class Test
<MTAThread> _
Shared Sub Main()
Dim newThreads(3) As Thread
For i As Integer = 0 To newThreads.Length - 1
newThreads(i) = New Thread(AddressOf SlotExample.SlotTest)
newThreads(i).Start()
Next i
End Sub
End Class
Public Class SlotExample
Shared randomGenerator As Random = New Random()
Shared Sub SlotTest()
' Set different data in each thread's data slot.
Thread.SetData( _
Thread.GetNamedDataSlot("Random"), _
randomGenerator.Next(1, 200))
' Write the data from each thread's data slot.
Console.WriteLine("Data in thread_{0}'s data slot: {1,3}", _
AppDomain.GetCurrentThreadId().ToString(), _
Thread.GetData( _
Thread.GetNamedDataSlot("Random")).ToString())
' Allow other threads time to execute SetData to show
' that a thread's data slot is unique to the thread.
Thread.Sleep(1000)
Console.WriteLine("Data in thread_{0}'s data slot is still: {1,3}", _
AppDomain.GetCurrentThreadId().ToString(), _
Thread.GetData( _
Thread.GetNamedDataSlot("Random")).ToString())
' Allow time for other threads to show their data,
' then demonstrate that any code a thread executes
' has access to the thread's named data slot.
Thread.Sleep(1000)
Dim o As New Other()
o.ShowSlotData()
End Sub
End Class
Public Class Other
Public Sub ShowSlotData()
' This method has no access to the data in the SlotExample
' class, but when executed by a thread it can obtain
' the thread's data from a named slot.
Console.WriteLine("Other code displays data in thread_{0}'s data slot: {1,3}", _
AppDomain.GetCurrentThreadId().ToString(), _
Thread.GetData( _
Thread.GetNamedDataSlot("Random")).ToString())
End Sub
End Class