开发者

When does an Action<T> get garbage collected?

I have an Event Aggregator that's using WeakReferences to store Action<T>. The problem I'm running into is that my actions keep getting garbage collected.

The following will fail...

public Foo(IEventAggregator eventAggregator)
{
   eventAggregator.Subscribe<BarEvent>(DoNo开发者_如何学运维thing)
}

public void DoNothing(BarEvent aEvent) {}

Yet the following will succeed...

private Action<BarEvent> _action;

public Foo(IEventAggregator eventAggregator)
{
  _action = DoNothing;
  eventAggregator.Subscribe<BarEvent>(_action);
}

public void DoNothing(BarEvent aEvent) {}

Obviously the _action variable is helping to keep things alive but I'm a bit confused as to why.. and more importantly is there a way to keep the action alive without the reference?


When does an Action get garbage collected?

When the garbage collector feels like it.

The WeakReference class is descibed thus:

Represents a weak reference, which references an object while still allowing that object to be reclaimed by garbage collection.

In other words you explicitly said that you don't mind if the object gets collected. You can't have your cake and eat it. Either take a strong reference or be prepared to recreate the object in case it has been collected.


i don't think you're going to get a valid "answer", since you are dealing with the undocumented internals of how garbage collector happens to run on your computer as it happens to be configured right now.

Change the garbage collector's:

  • LatencyMode
  • enable the multi-threaded garbage collector (gcConcurrent)
  • or switch to the server garbage collector (gcServer)

and you can expect different behavior.


Which makes my answer to your question: i don't know.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜