我已经实现了这个WeakEvent委托,但是由于某种原因,它只能工作几秒钟,之后便停止工作:

public class WeakEventHandler<TE>  where TE : EventArgs
{
    private readonly Action<WeakEventHandler<TE>> _unsubscriber;
    private readonly WeakReference<EventHandler<TE>> _targetRef;
    private readonly EventHandler<TE> _handler;


    public WeakEventHandler(EventHandler<TE> eventReceiver, Action<WeakEventHandler<TE>> unsubscriber)
    {
        _unsubscriber = unsubscriber;
        _targetRef = new WeakReference<EventHandler<TE>>(eventReceiver);
        _handler = Invoke;
    }

    public void Invoke(object sender, TE e)
    {
        EventHandler<TE> method;

        if (_targetRef.TryGetTarget(out method))
        {
            method(sender, e);
        }
        else
        {
            _unsubscriber(this);
        }

    }

    public static implicit operator EventHandler<TE>(WeakEventHandler<TE> weh)
    {
        return weh._handler;
    }
}

public static class EventHandlerUtils
{
    public static EventHandler<TE> MakeWeak<TE>(this EventHandler<TE> eventReceiver, Action<WeakEventHandler<TE>> unsubscriber) where TE : EventArgs
    {
        return new WeakEventHandler<TE>(eventReceiver, unsubscriber);
    }
}


用法:

    private EventHandler<MouseInteractionArgs> _mouseInteractionDelegate;

    public event EventHandler<MouseInteractionArgs> MouseAction
    {
        add
        {
            _mouseInteractionDelegate += value.MakeWeak(handler => _mouseInteractionDelegate -= handler );
        }

        remove
        {
            throw new InvalidOperationException("This is a weak Event, dont worry about unsubscribing");
        }
    }


我从未停止引用该方法的所有者,所以我不知道为什么它不起作用,委托的行为是否有所不同?

最佳答案

但“ eventreceiver”由该方法的实例拥有


抱歉,但是您已经倒退了。 “ eventReceiver”是您要添加到MouseAction事件的委托实例。该委托实例保留对目标对象和MethodInfo的引用,而不是相反。除了您的WeakReference以外,没有代码保留对委托实例的引用,当然,根据设计,这不足以使对象保持活动状态。

09-20 15:51