Using a weak event in .NetCore

It seems that weak events or more specifically the WeakEventManager or IWeakEventListener not available in .Net Core, as they are part of the WindowsBase assembly.

Are there alternatives to this feature?

Events are often a source of memory leaks in applications, and weak links are a great way to handle this problem.

I could not find information on this topic in stackoverflow

+6
source share
1 answer

The Nito.Mvvm.Core library has a WeakCanExecuteChagned that makes weak events using a class of commands that you could use as a starting point for writing your manager, supported by WeakCollection<EventHandler> .

Here is a simple example of using a custom class with an event named Foo that accepts a FooEventArgs object.

 public class MyClass { private readonly WeakCollection<EventHandler<FooEventArgs>> _foo = new WeakCollection<EventHandler<FooEventArgs>>(); public event EventHandler<FooEventArgs> Foo { add { lock (_foo) { _foo.Add(value); } } remove { lock (_foo) { _foo.Remove(value); } } } protected virtual void OnFoo(FooEventArgs args) { lock (_foo) { foreach (var foo in _foo.GetLiveItems()) { foo(this, args); } } } } 
+4
source

Source: https://habr.com/ru/post/1013137/


All Articles