Provide simple syntax to create a weak-referenced eventhandler
See original GitHub issueThe by far most common memory leak people introduce in .NET apps are caused by event handlers added to longer-lived objects. For instance an event on a static instance, or on an instance who’s lifetime is the entire app lifetime (like app view model or app settings). Listening for events on this from a shorter-lived object, makes this short-lived object hang around in memory until the app stops running. A common scenario is the INotifyCollectionChanged event listened to by a XAML control, with data coming from a collection provided by some app state. This will cause a very memory-consuming object like a UIElement to stay around in memory until the app closes. The recommended pattern to avoid this is by using WeakReference preferable wrapped in an event manager / event proxy class. However this can be quite a lot of code to write, and the implementation is not straight forward, and will still cause the small proxy hang around at least until the event fires again (if it ever does).
It would be much simpler if a syntax alternative to “+=” would denote “weak”. For example:
staticInstance.Data.CollectionChanged += MyChangedHandler; //not weak event reference
staticInstance.Data.CollectionChanged +~ MyChangedHandler; //weak event reference
I’m not saying ‘+~’ should actually be the syntax - just that we have something as simple as this to solve a very common scenario.
Uservoice suggestion for voting: http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/7019993-provide-simple-syntax-to-create-a-weak-referenced
Issue Analytics
- State:
- Created 9 years ago
- Reactions:23
- Comments:30 (10 by maintainers)
Top GitHub Comments
@gafter Could you please elaborate on what was discussed? I don’t understand why this needs to be in a library. We can already write it in code, and its tedious ugly code - even after using helper-methods in a library, and that still creates tiny memory leaks.
The entire purpose of the language proposal was to help people consider avoiding these types of memory leaks by making a much much easier no-brainer way to do this.
The memory leaks are a implementation problem, but I do not believe that’s what @dotMorten is concerned with. As I understand it, he’s looking for syntactic sugar that makes use of weak references cleaner to write/read.