Action何时执行?收集垃圾吗?

发布于 2024-12-09 15:33:14 字数 611 浏览 0 评论 0原文

我有一个事件聚合器,它使用 Wea​​kReferences 来存储 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

方圜几里 2024-12-16 15:33:14

什么时候 Action 会被垃圾回收?

当垃圾收集器有这样的感觉时。

WeakReference 类的描述如下:

表示弱引用,它引用一个对象,同时仍然允许垃圾收集回收该对象。

换句话说,您明确表示您不介意该对象是否被收集。你不能鱼与熊掌兼得。要么采用强引用,要么准备在对象被收集时重新创建该对象。

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.

微凉 2024-12-16 15:33:14

我不认为你会得到一个有效的“答案”,因为你正在处理垃圾收集器如何在你的计算机上运行的未记录的内部结构,因为它恰好是现在配置的。

更改垃圾收集器的:

,您可以期待不同的行为。


这就是我对你问题的回答:我不知道。

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:

and you can expect different behavior.


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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文