Rudey
Rudey

Reputation: 4965

NullReferenceException: Threading in a .NET structure?

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?

Upvotes: 1

Views: 522

Answers (1)

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239764

The problem is the delegate that is constructed when you use AddressOf. Delegates are constructed using an Object reference (for instance methods). The structure, necessarily, is boxed when it is passed as an Object, and will be unboxed before Start is called. It is this second, unboxed, copy of your structure that the Start method mutates.

Your original code, still working with the unboxed original structure, will see no modifications.

Upvotes: 3

Related Questions