public abstract class LivetWeakEventListener : IDisposable
{
public abstract void Dispose();
}
public class LivetWeakEventListener<TDelegate, TEventArgs> : LivetWeakEventListener where TEventArgs : EventArgs
{
private bool _disposed = false;
private EventHandler<TEventArgs> _handler;
private TDelegate _resultHandler;
private Action<TDelegate> _remove;
private static void ReceiveEvent(WeakReference listenerWeakReference, object sender, TEventArgs args)
{
var listener = listenerWeakReference.Target as LivetWeakEventListener<TDelegate, TEventArgs>;
if (listener != null)
{
var handler = listener._handler;
if (handler != null)
{
handler(sender, args);
}
}
}
private static TDelegate GetStaticHandler(WeakReference listenerWeakReference, Func<EventHandler<TEventArgs>, TDelegate> conversion)
{
return conversion((sender, e) => ReceiveEvent(listenerWeakReference, sender, e));
}
private LivetWeakEventListener() { }
public LivetWeakEventListener
(Func
<EventHandler
<TEventArgs
>, TDelegate
> conversion
, Action
<TDelegate
> add
, Action
<TDelegate
> remove, EventHandler
<TEventArgs
> handler
) {
_handler = handler;
_resultHandler = GetStaticHandler(new WeakReference(this), conversion);
add(_resultHandler);
}
public override void Dispose()
{
GC.SuppressFinalize(this);
this.Dispose(true);
}
private void Dispose(bool disposing)
{
if (_disposed) return;
_disposed = true;
_remove(_resultHandler);
}
~LivetWeakEventListener()
{
Dispose(false);
}
}
ICAgIHB1YmxpYyBhYnN0cmFjdCBjbGFzcyBMaXZldFdlYWtFdmVudExpc3RlbmVyIDogSURpc3Bvc2FibGUKICAgIHsKICAgICAgICBwdWJsaWMgYWJzdHJhY3Qgdm9pZCBEaXNwb3NlKCk7CiAgICB9CgogICAgcHVibGljIGNsYXNzIExpdmV0V2Vha0V2ZW50TGlzdGVuZXI8VERlbGVnYXRlLCBURXZlbnRBcmdzPiA6IExpdmV0V2Vha0V2ZW50TGlzdGVuZXIgd2hlcmUgVEV2ZW50QXJncyA6IEV2ZW50QXJncwogICAgewogICAgICAgIHByaXZhdGUgYm9vbCBfZGlzcG9zZWQgPSBmYWxzZTsKCiAgICAgICAgcHJpdmF0ZSBFdmVudEhhb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