为什么ASMX WebMethod中的finally块要写成Close和Dispose

发布于 2024-11-14 18:17:09 字数 434 浏览 2 评论 0原文

我正在考虑修改 ASMX 中的旧式 WebMethod,对于 Oracle 连接,我看到这些 finally 块重复了一千次。我最终想将其转换为 WCF,但现在这有什么问题吗?

finally
{
    if (command != null)
    {
        command.Dispose();
        command = null;
    }
    if (connection != null)
    {
        connection.Close();
        connection.Dispose();
        connection = null;
    }
    if (adapter != null)
    {
        adapter.Dispose();
        adapter = null;
    }
}

I'm looking at modifying an old school WebMethod in ASMX and for the Oracle connections, I am seeing these finally blocks repeated a thousand times. I eventually want to convert this over to WCF but for now what is wrong with this ?

finally
{
    if (command != null)
    {
        command.Dispose();
        command = null;
    }
    if (connection != null)
    {
        connection.Close();
        connection.Dispose();
        connection = null;
    }
    if (adapter != null)
    {
        adapter.Dispose();
        adapter = null;
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

猫九 2024-11-21 18:17:09

这个想法是清理与 Oracle 数据库连接相关的所有内容、对其执行的任何命令以及使用的任何数据适配器。

将此代码放在 finally 块中可确保关闭连接,并释放其调用所使用的资源并进行垃圾收集。

这没有什么问题,但是这个逻辑可以被抽象出来,这样就不必一遍又一遍地重复。

The idea is to clean up everything related to the connection to the Oracle database and any commands that were executed against it as well as any data adapters that were used.

Having this code in the finally block ensures that the connections are closed and the resources used by their invocation are disposed of and garbage collected.

There's nothing wrong with it, but this logic could be abstracted away so it doesn't have to be repeated over and over again.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文