When are event subscriptions with strong references actually desired/required?
I'll start with a description of the problem regarding events and strong references. Copied from here
It is often the case that the "subject" (the object with the event) has a longer lifetime than the "observer" (the object that subscribes to the event). When we are no longer using the observer, we would like it to be garbage collected; however, if the observer is still subscribed to an event on the subject, the associated event handler holds a strong reference to the observer, so the observer will not be garbage collected until the subject also becomes garbage, or until the obse开发者_如何学Gorver unsubscribes.
Having encountered that problem, i went looking for solutions. I have read the Weak Event Patterns article from MSDN, and have used that pattern several times. It felt bloated. I went looking for something better and came across these two blog posts:
- Event subscription using weak references
- Solving the Problem with Events: Weak Event Handlers
That makes things a lot easier. So now that i have an easy way to use weak event subscriptions, i start wondering, when should i use a weak event? Turns out i can't think of a reason not to use weak events.
My question is: when would you want the subject to hold a strong reference the listener? In what kind of design would it be logical/desirable for the subject to be the only thing keeping the listener alive. If the listener accomplishes a certain tasks in your application, isn't there always a "normal" reference to it?
I'm looking at this through WPF-colored glasses, and am particularly interested in WPF-related uses of strong references. But non-WPF-related answers would also be appreciated, if only just to be aware of those uses.
public class MyForm : Form
{
public MyForm()
{
this.Closed += delegate
{
MessageBox.Show("If events were weak by default, you might never see this message.");
};
}
}
It would be nice if the weak event pattern was a more intrinsic part of .NET, however.
This is not an answer to the question. It is merely an attempt to get you to stop beating on this particular dead horse.
Why is there no CLR support for weak events?
A) There is not sufficient demand for them. I don't believe this to be true. Look at the ugly bloat that WPF added to support them.
B) WPF contains ugly bloat to support weak events. If anyone could have pressured the CLR team to finally get around to providing CLR support for weak events, don't you think the WPF team could have done it?
Therefore: We are never going to see CLR support for weak events.
精彩评论