Action何时执行?收集垃圾吗?
我有一个事件聚合器,它使用 WeakReferences 来存储 Action
。我遇到的问题是我的操作不断被垃圾收集。
以下内容将失败...
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 变量有助于保持事物的活力,但我对为什么有点困惑..更重要的是,有没有一种方法可以使动作保持活力而无需参考?
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>(DoNothing)
}
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当垃圾收集器有这样的感觉时。
WeakReference
类的描述如下:换句话说,您明确表示您不介意该对象是否被收集。你不能鱼与熊掌兼得。要么采用强引用,要么准备在对象被收集时重新创建该对象。
When the garbage collector feels like it.
The
WeakReference
class is descibed thus: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.
我不认为你会得到一个有效的“答案”,因为你正在处理垃圾收集器如何在你的计算机上运行的未记录的内部结构,因为它恰好是现在配置的。
更改垃圾收集器的:
LatencyMode
gcConcurrent
)gcServer
),您可以期待不同的行为。
这就是我对你问题的回答:我不知道。
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
gcConcurrent
)gcServer
)and you can expect different behavior.
Which makes my answer to your question: i don't know.