CommunityToolkit icon indicating copy to clipboard operation
CommunityToolkit copied to clipboard

Best case senarios on when to use WeakReferenceMessenger Vs StrongReferenceMessenger

Open JawadJaber opened this issue 2 years ago • 1 comments

Although the explanation is clear on the messenger, it would be better to show best case scenarios for when to use either of the messenger options (weak and strong). shall I assume I have to use Strong type on UWP, WPF and the weak on the mobile devices? and Why the default examples are for WeakReferenceMessenger only?


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

JawadJaber avatar Oct 04 '21 06:10 JawadJaber

FYI @Sergio0694

@JawadJaber there's no correlation to platforms. Strong/Weak refers to the Reference in its name, which as the docs call out in the opening paragraph refers to a reference to the recipient. (Maybe we need a paragraph break there.)

The MVVM Toolkit provides two implementations out of the box: WeakReferenceMessenger and StrongReferenceMessenger: the former uses weak references internally, offering automatic memory management for recipients, while the latter uses strong references and requires developers to manually unsubscribe their recipients when they're no longer needed (more details about how to unregister message handlers can be found below), but in exchange for that offers better performance and far less memory usage.

By using the WeakReferenceMessenger you give up a bit of performance (and was memory but that's moot in the next version if running on .NET 6) for not having to worry about unregistering for messages when your receiver object's lifecycle is completed.

Using the StrongReferenceMessenger means you have to manually unregister for the messages you were listening for when you're done with your object. Otherwise the messenger will hold a reference to it and you'll introduce a memory leak. However, the StrongReferenceMessenger is faster and uses no memory.

The difference will be fairly negligible moving forward, but since the WeakReferenceMessenger is easier to use and what folks would be familiar with coming from MVVMLight, we show that in the examples.

Only difference in the example would needing to add a call to Unregister, though @Sergio0694 probably a good idea to have a section at the bottom that shows that and talks a bit more about how to handle that for StrongReferenceMessenger.

michael-hawker avatar Dec 10 '21 22:12 michael-hawker