Guest User

Untitled

a guest
Apr 20th, 2018
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. Imports CallContext = System.Runtime.Remoting.Messaging.CallContext
  2. Imports ILogicalThreadAffinative = System.Runtime.Remoting.Messaging.ILogicalThreadAffinative
  3.  
  4.  
  5. 'OUTPUT:
  6. '
  7. 'During STA - Hello World!!!
  8. 'Setting to 134731742
  9. 'After STA - Hello World!!!
  10. 'During MTA - Hello World!!!
  11. 'Setting to 553887779
  12. 'After MTA - Hello World!!!
  13. 'Complete
  14.  
  15.  
  16.  
  17. Module Module1
  18.  
  19. Private _ewh As New Threading.EventWaitHandle(False, Threading.EventResetMode.AutoReset)
  20.  
  21. Sub Main()
  22. FooContext.SetContext("Hello World!!!")
  23.  
  24. Dim threadSTA As New Threading.Thread(AddressOf DoInvoke)
  25. threadSTA.SetApartmentState(Threading.ApartmentState.STA)
  26. threadSTA.Start(Function() DoTest("STA", _ewh))
  27. _ewh.WaitOne()
  28. Console.WriteLine("After STA - {0}", FooContext.GetFoo)
  29.  
  30. Dim threadMTA As New Threading.Thread(AddressOf DoInvoke)
  31. threadMTA.SetApartmentState(Threading.ApartmentState.MTA)
  32. threadMTA.Start(Function() DoTest("MTA", _ewh))
  33. _ewh.WaitOne()
  34. Console.WriteLine("After MTA - {0}", FooContext.GetFoo)
  35.  
  36. Console.WriteLine("Complete")
  37. Console.ReadKey()
  38. End Sub
  39.  
  40. Private Sub DoInvoke(ByVal del As [Delegate])
  41. del.DynamicInvoke()
  42. End Sub
  43.  
  44. Private Function DoTest(ByVal msg As String, ByVal ewh As Threading.EventWaitHandle) As Integer
  45. Dim rnd As Random = New Random
  46. Dim rndNum As Integer = rnd.Next
  47.  
  48. Console.WriteLine("During {0} - {1}", msg, FooContext.GetFoo)
  49. Console.WriteLine("Setting to {0}", rndNum)
  50.  
  51. FooContext.SetContext(rndNum.ToString)
  52.  
  53. ewh.Set()
  54. Return 0
  55. End Function
  56.  
  57.  
  58. <Serializable()> _
  59. Public Class FooContext
  60. Implements ILogicalThreadAffinative
  61.  
  62. Private Const CONTEXTKEY As String = "FooContext"
  63.  
  64. Public Foo As String
  65.  
  66. Public Sub New(ByVal _foo As String)
  67. Foo = _foo
  68. End Sub
  69.  
  70. Public Shared Sub SetContext(ByVal _foo As String)
  71. CallContext.SetData(CONTEXTKEY, New FooContext(_foo))
  72. End Sub
  73.  
  74. Public Shared Function GetFoo() As String
  75. Dim o As Object = CallContext.GetData(CONTEXTKEY)
  76. If o Is Nothing OrElse Not TypeOf o Is FooContext Then Return "Invalid"
  77. Return DirectCast(o, FooContext).Foo
  78. End Function
  79.  
  80. End Class
  81.  
  82. End Module
Add Comment
Please, Sign In to add comment