为什么ASMX WebMethod中的finally块要写成Close和Dispose
我正在考虑修改 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这个想法是清理与 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.