It looks like the Weak Events or more specifically WeakEventManager
or IWeakEventListener
are not available in .Net Core as they are part of WindowsBase assembly.
Are there an alternatives to this feature?
Events are often a source of memory leaks in applications and weak references are a great way of dealing with this issue.
I couldn't find any information on this topic in stackoverflow
The library Nito.Mvvm.Core has a WeakCanExecuteChagned
class that does weak events using the command class you could use as a starting point for writing your manager backed by a WeakCollection<EventHandler>
.
Here is a simple example using a custom class with a event named Foo
that takes in 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);
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With