Search code examples
vb.netraiseevent

RaiseEvent triggers a "Debugger.Runtime.CrossThreadMessagingException"


I have a class in VB.NET that has a method (called CurrentValue) that returns a number. There is also an event that the class raises to indicate the number has changed. In the event handler on my form, I update a textbox using the exposed method.

Sort of like this:

Public WithEvents MyClass as New CustomClass   

Private Sub MyClass_DataChanged() Handles MyClass.DataChanged
    Text1.Text = MyClass.CurrentValue
End Sub

When I run this I get a "Debugger.Runtime.CrossThreadMessagingException" error. What could be doing this? I am instantiating MyClass in the same form that contains the textbox.

I can also set properties of the MyClass object without any trouble.


Solution

  • OK, here's what I did:

    In the form I have this to handle the event:

    Public Delegate Sub MyClassDataChangedDelegate()
    Sub MyClassDataChanged() Handles MyClass.DataChanged
        If Me.InvokeRequired Then
            Me.Invoke(New MyClassDataChangedDelegate(AddressOf MyClassDataChanged))
        Else
            Me.Text1.Text = MyClass.CurrentValue
        End If
    End Sub
    

    This seems to work. Thanks for the suggestion.