我有一個使用WeakReferences存儲Action<T>
的事件聚合器。我遇到的問題是我的行爲不斷收集垃圾。什麼時候動作<T>得到垃圾回收?
下會失敗......
public Foo(IEventAggregator eventAggregator)
{
eventAggregator.Subscribe<BarEvent>(DoNothing)
}
public void DoNothing(BarEvent aEvent) {}
然而,下面會成功...
private Action<BarEvent> _action;
public Foo(IEventAggregator eventAggregator)
{
_action = DoNothing;
eventAggregator.Subscribe<BarEvent>(_action);
}
public void DoNothing(BarEvent aEvent) {}
顯然_action變量幫助保持東西還活着,但我有點困惑至於爲什麼..更重要的是,有沒有一種方法可以保持行動沒有參考?
你爲什麼在這裏使用WeakReferences?他們假設你對其他地方的特定項目有非弱的參考... – Joe
因爲我不想要事件彙總。永遠保持周圍事物。我的問題更多..如果Foo沒有被GC'ed ..爲什麼行動被GC'ed?它只是在創造它的方法的生命中才存在嗎? –