Jindrich Vavruska
Jindrich Vavruska

Reputation: 832

VB.net form receiving events after being closed

In Forms application I open a form which uses an object to communicate with serial port. The communication object raises a class event when some data are received from serial port and are checked to be valid. Problem: after I close the form, there should be no further communication. For instance, I want another form to communicate. Unfortunately, even after I close the form, it keeps on receiving and handling the incoming data, which in fact causes interference with other processes in the application. The actual code is too complex to show here, but to illustrate, let's assume three different classes/forms:

The problem is that once the DataCollectionForm class is instantiated and shown, it handles all messages from Communicator, even after the form is closed. The event handler sort of "hangs" even though the form object itself is no longer valid (or, rather, should no longer be valid).

Upvotes: 0

Views: 40

Answers (1)

John
John

Reputation: 3182

You need to remove the event handler registration(s). If you have a Handles clause on your event handlers, set the field specified to Nothing. If you used AddHandler to register the event handler, you need to use RemoveHandler to unregister it. That means that you need to keep a reference to the object that raises the event. E.g.

Private WithEvents someObject As new SomeType
Private someOtherObject As SomeOtherType

Private Sub DoSomething()
    someOtherObject = New SomeOtherType
    AddHandler someOtherObject.SomeOtherEvent, AddressOf SomeOtherObject_SomeOtherEvent
End Sub

Private Sub SomeObject_SomeEvent(sender As Object, e As EventArgs) Handles someObject.SomeEvent
    '...
End Sub

Private Sub SomeOtherObject_SomeOtherEvent(sender As Object, e As EventArgs)
    '...
End Sub

Private Sub Form1_FormClosed(sender As Object, e As EventArgs) Handles Me.FormClosed
    someObject = Nothing
    RemoveHandler someOtherObject.SomeOtherEvent, AddressOf SomeOtherObject_SomeOtherEvent
    someOtherObject = Nothing
End Sub

Upvotes: 2

Related Questions