Whenever I call the constructor of the following Structure (with the parameter set to True) I get a NullReferenceException:
Imports System.Threading
Imports System.Windows.Threading
Public Structure Test
Private MyDispatcher As Dispatcher
Private MyResetEvent As ManualResetEvent
Public Sub New(ByVal newThread As Boolean)
If newThread Then
MyResetEvent = New ManualResetEvent(False)
Dim thread As New Thread(AddressOf Start)
thread.Start()
MyResetEvent .WaitOne()
' NullReferenceException below:
MyDispatcher.BeginInvoke(New Action(AddressOf DoSomething))
End If
End Sub
Private Sub Start()
MyDispatcher = Dispatcher.CurrentDispatcher
MyResetEvent.Set()
Dispatcher.Run()
End Sub
Private Sub DoSomething()
End Sub
End Structure
MyDispatcher is Nothing, which causes the NullReferenceException. But using a Class instead of a Structure works just fine. Why?
Edit: And what workarounds are possible?
The problem is the delegate that is constructed when you use
AddressOf. Delegates are constructed using anObjectreference (for instance methods). The structure, necessarily, is boxed when it is passed as anObject, and will be unboxed beforeStartis called. It is this second, unboxed, copy of your structure that theStartmethod mutates.Your original code, still working with the unboxed original structure, will see no modifications.