sharkyenergy
sharkyenergy

Reputation: 4173

.net why need to dispose handles when closing program

according to this documentation i have to dispose the handles when i close the program.

https://infosys.beckhoff.com/english.php?content=../content/1033/tcquickstart/html/tcquickstart_samplevisualbasicnet.htm&id=

 '------------------------------------------
    'wird beim Beenden des Programms aufgerufen
    'is activated when ending the program
 '------------------------------------------
Private Sub frmMachine_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
    Try
        ' Löschen der Notifications und Handles
        ' Deleting of the notifications and handles
        tcClient.DeleteDeviceNotification(hEngine)
        tcClient.DeleteDeviceNotification(hDeviceUp)
        tcClient.DeleteDeviceNotification(hDeviceDown)
        tcClient.DeleteDeviceNotification(hSteps)
        tcClient.DeleteDeviceNotification(hCount)
        tcClient.DeleteDeviceNotification(hSwitchNotify)

        tcClient.DeleteVariableHandle(hSwitchWrite)
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
    tcClient.Dispose()
End Sub

Is it needed? Isn't the memory freed up anyway when I close the program? Could it happen that the handle is present multiple times if the program is closed and then reopened?

Upvotes: 0

Views: 115

Answers (1)

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239764

It's in the form closing event, which, okay, yes, if you're building a single form application will also be when the program closes but I think is probably meant to be illustrative of the general principle that you clean up after you're done using things.

You're right in general that if the program's about to exit, you don't need to do such tidying. As Raymond Chen puts it:

The building is being demolished. Don’t bother sweeping the floor and emptying the trash cans and erasing the whiteboards. And don’t line up at the exit to the building so everybody can move their in/out magnet to out. All you’re doing is making the demolition team wait for you to finish these pointless housecleaning tasks.

OS handles will be reclaimed when the process exits. However, if you're communicating with external hardware, it may be cleaner to delete the handles if this places the hardware back into a known-good state (this does beg the question of what's meant to happen if your program crashes however)

Upvotes: 1

Related Questions