Can I make a C# object's lifetime depend on another object?

I have an object (Delegate) which needs to stay alive (not garbage collected) while another object (TargetObject) is alive. I want Delegate to be garbage collected when TargetObject is collected (or at least available for collection).

The difficulty is that I don't want to need to reference Delegate from TargetObject since I want it to work for existing objects unaware of Delegate, and I don't want to affect the lifetime of TargetObject. Is this at all possible?

Thanks.

Edit: Thanks for the responses so far. I'll try to clarify what I'm up to.

I'm trying to implement weak events but I'm not a fan of the WeakEventManager (particularly IWeakEventListener). I want to hold a weak reference to a delegate event handler (Delegate) which points to a method in object TargetObject. There needs to be a strong reference to Delegate while TargetObject is alive to keep Delegate alive, but if something with a longer lifetime references Delegate, it keeps TargetObject alive (defeating the purpose of the weak event).

It would be nice if objects subscribing to weak events didn't have to have any special implementation details such as having to hold on to a collection of delegates.

Edit Edit: Changed 'A' to 'Delegate' and 'B' to 'TargetObject'


Holy necro, but ConditionalWeakTable does just what you needed. It allows associating values with arbitrary keys, with the key value pairs as ephemerons (exactly what you were looking for, 2 years ago now.. unfortunately .NET 4 wasn't available then).

Even without ConditionalWeakTable a solution could have been a Dictionary<WeakReference, Delegate> , with periodic sweeping to remove old dead values (ie whenever the Dictionary doubles in size, remove all dead pairs). With this solution if a Delegate refers to TargetObject it'd prevent collection of the pair though - a problem ConditionalWeakTable was designed to resolve.

Just posting this in case anyone might find it useful.


This sounds like a design issue to me. If B doesn't need to know about the instance of A, why do you care about whether A is alive or not?

You can possibly do this using a container object with a weak reference to B and a strong reference to A, and a timer periodically checking whether the weak reference is still alive... but it would be a pretty grotty hack.

If you can explain why you think you need this, we may be able to suggest a better approach.


Why don't you just reference A from B?
That will keep A alive and does not require A to be aware of B...

链接地址: http://www.djcxy.com/p/51514.html

上一篇: .NET中的事件和内存泄漏

下一篇: 我可以使C#对象的生命周期取决于另一个对象吗?