2020-06-24:如何在写代码中,安全的关闭连接?

福哥答案2020-06-24:

java:
1.finally;
2.try-with-resource,类必须实现AutoCloseable接口;
3.finalize(),不一定安全,慎用。

c#:
1.finally;
2.using,类必须实现IDisposable接口;
3.析构,不一定安全,慎用。

golang:
1.defer;
2.runtime.SetFinalizer,析构,不一定安全,慎用。

python:
1.finally+hasattr+callalble;
finally:
    if hasattr(sftp_client, "close") and callable(sftp_client.close):
        sftp_client.close()
    if hasattr(ssh_conn, "close") and callable(ssh_conn.close):
        ssh_conn.close()
2.del析构函数,不一定安全,慎用。

原文地址:https://www.cnblogs.com/waitmoon/p/13442740.html