Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Weak Event in .NetCore

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

like image 603
Mohsen Shakiba Avatar asked Dec 13 '16 21:12

Mohsen Shakiba


1 Answers

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);
            }
        }
    }
}
like image 54
Scott Chamberlain Avatar answered Oct 13 '22 16:10

Scott Chamberlain