Reputation: 832
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:
Communicator class: it has method to send data, it checks incoming data by polling the serial port using timer, validates received data and once the incoming data form a valid message, it raises custom event (e.g. DataReceivedEvent). When expected message is not complete within a required time limit, it raises DataTimeoutEvent.
ConfigurationForm class: it communicates with the serial port via Communicator. It has event handlers for both the DataReceivedEvent and the DataTimeoutEvent. The messages received are basically acknowledgements of configuration commands sent to a device via serial port.
DataCollectionForm class: it communicates with the serial port via Communicator. It has event handlers for both the DataReceivedEvent and the DataTimeoutEvent. It analyses and visualises data received, but the relevant message types are different than those used by ConfigurationForm.
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
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