gpt4 book ai didi

datatable - 我应该 Dispose() DataSet 和 DataTable 吗?

转载 作者:太空宇宙 更新时间:2023-11-03 16:45:02 30 4
gpt4 key购买 nike

DataSet 和 DataTable 都实现了 IDisposable,因此,根据传统的最佳实践,我应该调用它们的 Dispose() 方法。

但是,据我目前所读的内容,DataSet 和 DataTable 实际上没有任何非托管资源,因此 Dispose() 实际上并没有做太多事情。

另外,我不能只使用 using(DataSet myDataSet...) 因为 DataSet 有一个 DataTable 集合。

因此,为了安全起见,我需要遍历 myDataSet.Tables,处理每个 DataTable,然后处理 DataSet。

那么,对我所有的数据集和数据表调用 Dispose() 是否值得?

附录:

对于那些认为应该处置 DataSet 的人:一般来说,disposing 的模式是使用 usingtry..finally,因为你想保证 Dispose() 会被调用。

但是,对于一个集合来说,这很快就会变得很丑陋。例如,如果对 Dispose() 的调用之一抛出异常,您会怎么做?你吞下它(这是“坏的”)以便你可以继续处理下一个元素吗?

或者,您是否建议我只调用 myDataSet.Dispose(),而忘记处理 myDataSet.Tables 中的 DataTable?

最佳答案

这里有几个讨论解释了为什么 Dispose 对于 DataSet 不是必需的。

To Dispose or Not to Dispose ? :

The Dispose method in DataSet exists ONLY because of side effect of inheritance-- in other words, it doesn't actually do anything useful in the finalization.

Should Dispose be called on DataTable and DataSet objects?包括来自 MVP 的一些解释:

The system.data namespace (ADONET) does not contain unmanaged resources. Therefore there is no need to dispose any of those as long as you have not added yourself something special to it.

Understanding the Dispose method and datasets?有来自权威斯科特艾伦的评论:

In pratice we rarely Dispose a DataSet because it offers little benefit"

因此,共识是目前没有充分的理由在 DataSet 上调用 Dispose。

关于datatable - 我应该 Dispose() DataSet 和 DataTable 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6325807/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com