.net 为什么关闭程序时需要处理句柄

.net why need to dispose handles when closing 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

需要吗?当我关闭程序时,内存不会被释放吗?程序关闭再打开会不会出现句柄多次出现的情况?

它在表单关闭事件中,好吧,是的,如果你正在构建一个单一的表单应用程序,那么程序关闭时也会发生,但我认为这可能是为了说明 一般使用完东西就清理的原则。

你是对的,一般来说,如果程序即将退出,你不需要做这样的整理。作为 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句柄会在进程退出时回收。但是,如果您正在与外部硬件通信,删除句柄可能会更干净,如果这会使硬件回到已知的良好状态(这确实回避了如果您的程序崩溃会发生什么的问题)