简体   繁体   中英

.net c# WeakEventManager theory and practical usage

Hi i have not clear about usage of WeakEventManager in .net.

I know difference between strong and week reference.

  1. strong is keeped until the unsubscribe is not happend.
  2. week - when GC collect is called => "non-deterministict time"

In second case i colld miss the events because listener can be randomly removed. Or i missed something?

For example MVVM community toolkit using this pattern for send/recieve messages between view models. But when can be "randomly" removed the message never comes.

Can you someone explain me this pattern and safety? Thanks

A normal reference to an object is a strong reference. Also, .Net provides a special class for creating weak references to objects for special cases. Microsoft docs says that GC cannot collect an object in use by an application while the application's code can reach that object. The application is said to have a strong reference to the object. (Look here for weak reference explanation Microsoft Wark Reference documentation ).

So, a listener cannot randomly be removed from memory while it is still in use by the application, in other words while it still has strong reference to it. For example, a window's DataContext property that refers to a view model class is a strong reference to the view model. If you use the weak event manager, it only keeps weak references to registered listeners so if no other strong reference is found (because the rest of the application do not use the object anymore), then GC will be allowed to collect the object. As far as the application is concerned, it does not cause any problem since the application doesn't use the object anyway.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM