Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Imports CallContext = System.Runtime.Remoting.Messaging.CallContext
- Imports ILogicalThreadAffinative = System.Runtime.Remoting.Messaging.ILogicalThreadAffinative
- 'OUTPUT:
- '
- 'During STA - Hello World!!!
- 'Setting to 134731742
- 'After STA - Hello World!!!
- 'During MTA - Hello World!!!
- 'Setting to 553887779
- 'After MTA - Hello World!!!
- 'Complete
- Module Module1
- Private _ewh As New Threading.EventWaitHandle(False, Threading.EventResetMode.AutoReset)
- Sub Main()
- FooContext.SetContext("Hello World!!!")
- Dim threadSTA As New Threading.Thread(AddressOf DoInvoke)
- threadSTA.SetApartmentState(Threading.ApartmentState.STA)
- threadSTA.Start(Function() DoTest("STA", _ewh))
- _ewh.WaitOne()
- Console.WriteLine("After STA - {0}", FooContext.GetFoo)
- Dim threadMTA As New Threading.Thread(AddressOf DoInvoke)
- threadMTA.SetApartmentState(Threading.ApartmentState.MTA)
- threadMTA.Start(Function() DoTest("MTA", _ewh))
- _ewh.WaitOne()
- Console.WriteLine("After MTA - {0}", FooContext.GetFoo)
- Console.WriteLine("Complete")
- Console.ReadKey()
- End Sub
- Private Sub DoInvoke(ByVal del As [Delegate])
- del.DynamicInvoke()
- End Sub
- Private Function DoTest(ByVal msg As String, ByVal ewh As Threading.EventWaitHandle) As Integer
- Dim rnd As Random = New Random
- Dim rndNum As Integer = rnd.Next
- Console.WriteLine("During {0} - {1}", msg, FooContext.GetFoo)
- Console.WriteLine("Setting to {0}", rndNum)
- FooContext.SetContext(rndNum.ToString)
- ewh.Set()
- Return 0
- End Function
- <Serializable()> _
- Public Class FooContext
- Implements ILogicalThreadAffinative
- Private Const CONTEXTKEY As String = "FooContext"
- Public Foo As String
- Public Sub New(ByVal _foo As String)
- Foo = _foo
- End Sub
- Public Shared Sub SetContext(ByVal _foo As String)
- CallContext.SetData(CONTEXTKEY, New FooContext(_foo))
- End Sub
- Public Shared Function GetFoo() As String
- Dim o As Object = CallContext.GetData(CONTEXTKEY)
- If o Is Nothing OrElse Not TypeOf o Is FooContext Then Return "Invalid"
- Return DirectCast(o, FooContext).Foo
- End Function
- End Class
- End Module
Add Comment
Please, Sign In to add comment