如果一个泛型集合实例化包含了IDisposable项目,做项目得到处置? [英] If a generic collection is instantiated to contain iDisposable items, do the items get disposed?

查看:150
本文介绍了如果一个泛型集合实例化包含了IDisposable项目,做项目得到处置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

Queue<System.Drawing.SolidBrush> brushQ = new Queue<System.Drawing.SolidBrush>();
...
brushQ.Clear();

如果我没有明确出列每个项目,并处理他们的个人,要求清除在做其余的项目得到处理()?如何当队列垃圾回收?

If I don't explicitly dequeue each item and dispose of them individually, do the remaining items get disposed when calling Clear()? How about when the queue is garbage collected?

假设答案是否,那么什么是最好的做法?你必须始终通过队列遍历和处置各项目?

Assuming the answer is "no", then what is the best practice? Do you have to always iterate through the queue and dispose each item?

这会变得非常恶劣,特别是如果你有try..finally围绕每个处理,以防其中一个会抛出异常。

That can get ugly, especially if you have to try..finally around each dispose, in case one throws an exception.

修改

所以,这似乎是一个负担,是一个泛型集合的用户知道,如果项目是一次性的(这意味着他们有可能被使用,不会被清理的垃圾收集非托管资源),然后:

So, it seems like the burden is on the user of a generic collection to know that, if the items are Disposable (meaning they are likely to be using unmanaged resources that won't be cleaned up by the garbage collector), then:

  1. 当你从集合中删除项目,请确保您的Dispose()吧。
  2. 请不要调用clear()。遍历 收集和处置各 项目。
  1. When you remove an item from the collection, make sure you Dispose() it.
  2. DON'T CALL Clear(). Iterate through the collection and dispose of each item.

也许对泛型集合的文档应该提到这一点。

Maybe the documentation for the generic collections should mention that.

推荐答案

当你期望他们进行处理?集合将如何知道是否有其他引用的对象呢?

When do you expect them to be disposed? How will the collection know if there are other references to the objects in it?

这篇关于如果一个泛型集合实例化包含了IDisposable项目,做项目得到处置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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