WeakEventManager保存对订户的引用

时间:2013-03-05 13:54:08

标签: c# closures weakeventmanager

我一直在使用WeakEventManager来避免内存泄漏,我开始过度使用它们。 我为例如INotifyPropertyChanged创建了扩展方法,如:


public static void AddWeakPropertyChanged(this INotifyPropertyChanged item, Action handler)
{
    PropertyChangedEventManager.AddHandler(item, (s, e) => handler(e.PropertyName), string.Empty);
}

现在我很快意识到,这不起作用。实际上,您无法真正使用匿名方法进行弱事件处理。 (如果我理解正确,那么编译器为它创建一个'闭包类'(用于保存引用的值),它具有处理程序,但由于你的闭包类没有在任何地方被引用,因此GC将清除它,并且事件处理程序将不会被召唤)

问题#1:这是正确的吗?我的意思是它是正确的,然后当使用匿名方法(或lambda)作为弱事件处理程序时,只有当GC没有同时运行时才调用处理程序(例如,它是不确定的)?

嗯,我知道,所以我做了一些单元测试,以确保我做对了。在我进行下面的单元测试之前,它似乎还可以:


        class DidRun
        {
            public bool Value { get; set; }
        }
        class TestEventPublisher
        {
            public event EventHandler<EventArgs> MyEvent;
            public void RaiseMyEvent()
            {
                if (MyEvent != null)
                    MyEvent(this, EventArgs.Empty);

            }
        }
        class TestClosure
        {
            public DidRun didRun { get; set; }
            public EventHandler<EventArgs> Handler { get; private set; }
            public TestClosure()
            {
                this.Handler = new EventHandler<EventArgs>((s, e) => didRun.Value = true);
            }
        }
        [TestMethod]
        public void TestWeakReference()
        {
            var raiser = new TestEventPublisher();
            var didrun = new DidRun();
            var closure = new TestClosure { didRun = didrun };
            WeakEventManager<TestEventPublisher, EventArgs>.AddHandler(raiser, "MyEvent", closure.Handler);
            closure = null;

            GC.Collect();
            GC.Collect();
            raiser.RaiseMyEvent();
            Assert.AreEqual(false, didrun.Value);
        }

问题2:任何人都可以解释为什么这个测试失败了?

期望:这里我没有任何闭包(我把它们拿出来,以确保发生了什么),我只是有一个对象(闭包),用WeakEventManager订阅一个事件,然后我删除了引用它(closure = null;)。

我期待2次GC.Collect()调用,以清理我的旧闭包类,因此WeakEventManager将删除订阅者,而不是运行处理程序,但测试失败。有什么想法吗?

编辑:抱歉,通用参数不可见,现在它们是

1 个答案:

答案 0 :(得分:3)

如果没有对它的引用,GC会收集你在lambda周围创建的闭包是正确的。

在单元测试中,您将TestClosure的本地实例清空,但是您已将处理程序的硬引用传递给WeakEventManager,而不是TestClosure的实例。所以处理程序依然存在......

我相信这些例子证明了你关闭的问题:

class DidRun
{
    public bool Value { get; set; }
}

class TestEventPublisher
{
    public event EventHandler<EventArgs> MyEvent;
    public void RaiseMyEvent()
    {
        if (MyEvent != null)
            MyEvent(this, EventArgs.Empty);
    }
}

class TestClosure
{
    static public EventHandler<EventArgs> Register(TestEventPublisher raiser, DidRun didrun)
    {
        EventHandler<EventArgs> handler = (s, e) => didrun.Value = true;
        WeakEventManager<TestEventPublisher, EventArgs>.AddHandler(raiser, "MyEvent", handler);
        return handler;
    }
}

[TestMethod]
public void Test1()
{
    var raiser = new TestEventPublisher();
    var didrun = new DidRun();

    TestClosure.Register(raiser, didrun);

    // The reference to the closure 'handler' is not being held,
    //  it may or may not be GC'd (indeterminate result)

    raiser.RaiseMyEvent();
    Assert.IsTrue(didrun.Value);
}

[TestMethod]
public void Test2()
{
    var raiser = new TestEventPublisher();
    var didrun = new DidRun();

    // The reference to the closure 'handler' is not being held, it's GC'd
    TestClosure.Register(raiser, didrun);

    GC.Collect();
    GC.Collect();

    raiser.RaiseMyEvent();
    Assert.IsFalse(didrun.Value);
}

[TestMethod]
public void Test3()
{
    var raiser = new TestEventPublisher();
    var didrun = new DidRun();

    // Keep local copy of handler to prevent it from being GC'd
    var handler = TestClosure.Register(raiser, didrun);

    GC.Collect();
    GC.Collect();

    raiser.RaiseMyEvent();
    Assert.IsTrue(didrun.Value);
}

至于您的原始问题,您可以尝试保存处理程序(闭​​包)以防止它被GC。 ConditionalWeakTable应该适用于此:

// ConditionalWeakTable will hold the 'value' as long as the 'key' is not marked for GC
static private ConditionalWeakTable<INotifyPropertyChanged, EventHandler<PropertyChangedEventArgs>> _eventMapping =
  new ConditionalWeakTable<INotifyPropertyChanged, EventHandler<PropertyChangedEventArgs>>();

public static void AddWeakPropertyChanged(this INotifyPropertyChanged item, Action<string> handlerAction)
{
    EventHandler<PropertyChangedEventArgs> handler;

    // Remove any existing handler for this item in case it's registered more than once
    if (_eventMapping.TryGetValue(item, out handler))
    {   
        _eventMapping.Remove(item);
        PropertyChangedEventManager.RemoveHandler(item, handler, string.Empty);
    }   

    handler = (s, e) => handlerAction(e.PropertyName);

    // Save handler (closure) to prevent GC
    _eventMapping.Add(item, handler);

    PropertyChangedEventManager.AddHandler(item, handler, string.Empty);
}

class DidRun
{
    static public string Value { get; private set; }
    public void SetValue(string value) { Value = value; }
}

[TestMethod]
public void Test4()
{
    var property = new ObservableObject<string>();

    var didrun = new DidRun();
    property.AddWeakPropertyChanged(
        (x) => 
        {
            didrun.SetValue("Property Name = " + x);
        });

    GC.Collect();
    GC.Collect();

    property.Value = "Hello World";

    Assert.IsTrue(DidRun.Value != null);
}