弱参考仍然存在

时间:2015-03-06 14:53:35

标签: c# garbage-collection weak-references

我有一个接口:IRemoteDataChangedListener

public interface IRemoteDataChangedListener<TData>
{
    void DataReceived(TData newData);
}

一个类,RealtimeEventService

public class RealtimeEventService : IRealtimeEventService
{
    private readonly IEventListener listener;

    private readonly List<Tuple<Type, WeakReference>> dataCreated;

    public RealtimeEventService(IEventListener eventListener)
    {
        this.dataCreated = new List<Tuple<Type, WeakReference>>();
        this.listener = eventListener;
        this.listener.EventReceived += this.ListenerOnEventReceived;
    }

    private void ListenerOnEventReceived(EventMessage message)
    {
        Type type = message.GetType();

        if (type == typeof(NotificationReadEventMessage))
        {
            this.DataChanged((NotificationReadEventMessage)message);
        }
    }

    public void SubscribeDataChanged<TEventMessage>(IRemoteDataChangedListener<TEventMessage> dataChangedListener) where TEventMessage : EventMessage, new()
    {
        this.dataCreated.Add(Tuple.Create(typeof(TEventMessage), new WeakReference(dataChangedListener)));
    }

    internal void DataChanged<TKey>(TKey newData)
        where TKey : class, new()
    {
        LoopAndFilter<TKey>(this.dataCreated, listener => listener.DataReceived(newData));
    }

    private static void LoopAndFilter<TKey>(ICollection<Tuple<Type, WeakReference>> collection,
        Action<IRemoteDataChangedListener<TKey>> success) where TKey : class
    {
        foreach (var reference in collection.ToArray())
        {
            if (!reference.Item2.IsAlive)
            {
                collection.Remove(reference);
                continue;
            }

            if (reference.Item1 != typeof(TKey))
                continue;

            success((IRemoteDataChangedListener<TKey>)reference.Item2.Target);
        }
    }

    #endregion
}

每当我创建一个继承IRemoteDataChangedListener并将NotificationReadEventMessage作为泛型参数的测试类,并使用此类的实例与SubscribeDataChanged()时,它就会很好地连接,并调用该方法。

问题是,当我将实例引用设置为null并运行GC.Collect()时,它应该为null,并且下次运行RealtimeEventService的LoopAndFilter方法时,它应该检测到它不再存活,并删除列表中的弱参考。

但事实并非如此。当我检查值(In LoopAndFilter)时,在测试中将实例引用设置为null后,该值仍显示为Alive为true。

现在我已经盯着这段代码好几个小时了,我根本找不到任何能够强烈引用这个代码的地方......

任何帮助?

@Edit:单元测试(使用Moq和Should库):

public class RealtimeEventServiceTests
{
    [Fact]
    public void VerifyWeakReferencesWorksAsIntended()
    {
        var eventListenerMock = new Mock<IEventListener>();
        IRealtimeEventService service = new RealtimeEventService(eventListenerMock.Object);

        bool called = false;
        RemoteDataTest dataChangedListener = new RemoteDataTest();
        dataChangedListener.Called += (sender, args) => called = true;
        service.SubscribeDataChanged(dataChangedListener);

        called.ShouldBeFalse();
        ((RealtimeEventService)service).DataChanged(new NotificationReadEventMessage());
        called.ShouldBeTrue();

        called = false;
        dataChangedListener = null;
        GC.Collect();

        called.ShouldBeFalse();
        ((RealtimeEventService)service).DataChanged(new NotificationReadEventMessage());
        called.ShouldBeFalse();
    }
}

public class RemoteDataTest : IRemoteDataChangedListener<NotificationReadEventMessage>
{
    public event EventHandler Called;

    public void DataReceived(NotificationReadEventMessage newData)
    {
        if (Called != null) Called(this, null);
    }
}

1 个答案:

答案 0 :(得分:0)

事实证明,当我回到家并在家编译它时,它运行得很好。当我回到工作岗位时,它也能很好地工作。

猜猜它只是那些在莫名其妙的时候神奇地消失的幽灵般的错误之一。我很高兴能够摆脱它。

我确实接受了Ewan&amp;的建议。斯科特张伯伦,谢谢你!