Example implementation of weak events using .NET's WeakEventManager

后端 未结 2 1762
时光取名叫无心
时光取名叫无心 2021-02-04 00:24

Is there an example implementation of weak events using .NET\'s WeakEventManager?

I\'m trying to implement it by following the \"Notes to Inheritors\" in the documentati

2条回答
  •  囚心锁ツ
    2021-02-04 00:53

    Sharp Observation is an open source project that has an easy to use implementation. You might want to take a look at their code or just use it as-is.

    Usage

    The MakeWeak() method returns a new delegate which invokes the same target as the original delegate, but holds a weak reference to the target so that the listener is not kept alive by the delegate:

    var handler= new PropertyChangingEventHandler(listener.HandleChange);
    observable.PropertyChanging += handler.MakeWeak();
    

    Limitations

    The current implementation has the following restrictions on delegates:

    • Return values are not supported.
    • Arguments of Out and Ref are not supported.

提交回复
热议问题