简体   繁体   中英

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

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);
            }
        }
    }
}

My library System.Waf.Core provides a WeakEvent implementation that can be used as an alternative to the WeakEventManager .

Example for INotifyPropertyChanged.PropertyChanged:

public class Publisher : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler? PropertyChanged;
}

public class Subscriber
{
    public void Init(Publisher publisher)
    {
        // Instead of publisher.PropertyChanged += Handler; use the following statement:
        WeakEvent.PropertyChanged.Add(publisher, Handler)        
    }

    public void Handler(object? sender, PropertyChangedEventArgs e) { }
}

More details can be found on this Wiki page Weak Event .

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