当对象变成孤立对象时,如何处置它(例如位图)? [英] How can I dispose of an object (say a Bitmap) when it becomes orphaned?

查看:100
本文介绍了当对象变成孤立对象时,如何处置它(例如位图)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个A类,可为其他B,C等类提供位图。

I have a class A providing Bitmaps to other classes B, C, etc.

现在,A类将其位图保存在环形队列中,因此过一会丢失对位图的引用。

Now class A holds its bitmaps in a ring queue so after a while it will lose reference to the bitmap.

虽然它仍在队列中,但同一位图可以由多个类检出,因此,例如B和C都可以容纳一个引用相同的位图。但是也可能发生这样的情况,只有其中一个签出位图,甚至根本都不签出。

While it's still in the queue, the same Bitmap can be checked out by several classes so that, say, B and C can both hold a reference to this same Bitmap. But it can also happen that only one of them checked out the Bitmap or even none of them.

我想在不再需要位图时将其丢弃

I would like to dispose of the bitmap when it's not being needed any more by either A, B or C.

我想我必须让B和C负责以某种方式告知他们何时完成使用,但我不确定

I suppose I have to make B and C responsible for somehow signaling when they're finished using it but I'm not sure about the overall logic.

应该是对诸如DisposeIfNowOrphan()之类的调用,在此示例中,它将被调用三次:

Should it be a call to something like DisposeIfNowOrphan() that would be called, in this example, three times :

1-当位图被踢出A类队列

1 - when the Bitmap gets kicked out of the queue in class A

2-当B完成后

3-C完成后

如果这是最好的策略,我如何评估孤儿状态?

If that's the best strategy, how can I evaluate the orphan state ?

任何建议都将受到欢迎。

Any advice would be most welcome.

推荐答案

A类提供了包装类而不是直接使用位图。包装器类应本身实现IDisposable,并可用于维护计数器。每个使用者都可以拥有引用相同位图的包装器。 A类保留所有位图和所有包装的陷阱。在A类中使用WeakReference来跟踪包装器,这样,如果消费者不致电处置,它将得到GC证明,而提供者可以知道不再引用它。

Have class A provide a wrapper class instead of a bitmap directly. The wrapper class should implement IDisposable itself and can be used to maintain a counter. Each consumer can get their own wrapper which references the same Bitmap. Class A keeps trap of all bitmaps and all wrappers. Use a WeakReference in Class A to keep track of the wrappers so if a consumer doesn't call dispose, it will get GC'd and the provider can know it's no longer referenced.

这篇关于当对象变成孤立对象时,如何处置它(例如位图)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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