处置的嵌套的一次性项目? [英] Dispose on nested Disposable items?

查看:154
本文介绍了处置的嵌套的一次性项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有关于处置嵌套在另一个一次性项目(在属性/公共领​​域,而不是私有成员)一次性项目的任何约定。例如,一个DataSet包含数据表(S)和一个SqlCommand包含一个SqlConnection。

最明显的事情是一类处置其拥有的所有一次性项目,并留下休息。是否存在这样的约定?如果是这样,如何​​.NET库确定谁拥有什么?我如何才能知道是否嵌套对象被设置?

PS:我一直想知道这一段时间,显然让其他人有:<一href="http://stackoverflow.com/questions/1828788/what-gets-disposed-when-sqlcommand-dispose-is-called">What被处置时SqlCommand.Dispose叫?

编辑1:发现,处理的数据集,不出售其表

  //填充数据集从sqldataadpater。
的foreach(在dataSet.Tables数据表DT)
{
    dt.Disposed + = Program.DisposedEventHandler2;
}
Console.WriteLine(转让数据集);
dataSet.Dispose(); //事件不是在这里发射。
Console.WriteLine(转让数据表maually);
的foreach(在dataSet.Tables数据表DT)
{
    dt.Dispose(); //触发的事件在这里
}
#endregion
 

解决方案

我的拇指一般遵循的原则是,创建一个一次性的对象的类,也将其丢弃。举个例子:一个的SqlCommand 不出售其连接,因为它没有创建它。该的StreamReader 有一个奇怪的行为,从这个意义上讲,因为它总是会处理底层流,即使是从外部供给的(我觉得这很烦人,请投<一个href="https://connect.microsoft.com/VisualStudio/feedback/details/577258/add-constructor-overload-to-streamreader-to-$p$pvent-it-to-dispose-the-underlying-stream"相对=nofollow>这里当你像微软来解决这个问题)。

I wanted to know if there are any conventions regarding disposal of disposable items nested inside another disposable item(in a property/public field, not as private members). For example, a DataSet contains DataTable(s) and a SqlCommand contains a SqlConnection.

The obvious thing would be for a class to dispose of all Disposable items it owns, and leave the rest. Does there exist such a convention? If it does, how does .NET libraries determine who owns what? How can I find out whether nested objects are being disposed?

PS: I have been wondering about this for a while, and apparently so have others : What gets disposed when SqlCommand.Dispose is called?

Edit 1 : Found out that disposing DataSet, does not dispose its tables.

// Fill dataset from sqldataadpater.
foreach (DataTable dt in dataSet.Tables)
{
    dt.Disposed += Program.DisposedEventHandler2;
}
Console.WriteLine("Disposing dataset");
dataSet.Dispose(); //Event not fired here.
Console.WriteLine("Disposing datatables maually");
foreach (DataTable dt in dataSet.Tables)
{
    dt.Dispose(); //Event fired here
}
#endregion

解决方案

The rule of thumb I normally follow is that the class that creates a disposable object, will also dispose it. As an example: a SqlCommand does not dispose its connection, because it didn't create it. The StreamReader has a strange behavior in this sense, because it will always dispose the underlying stream, even if it is supplied from the outside (I find this very annoying, please vote HERE when you like Microsoft to fix this).

这篇关于处置的嵌套的一次性项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆