Skip to content

Provide simple syntax to create a weak-referenced eventhandler #101

@dotMorten

Description

@dotMorten

The 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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions