1

我在 Flex 中有一个“框架”,它加载和销毁子“部分”,它们是模块类的实例。它们中有很多网络服务和动画,并且是面向公众的网站的一部分。

在我从屏幕上删除一个部分之前,我在实例上调用了一个“hideSection()”接口方法。在这种方法中,我会淡出任何控件,或者如果该部分想要防止自己被关闭,则返回 false。目前它还停止运行任何 Timer 实例。

问题是即使从舞台上移除了部分对象,也可能会有一些未完成的事情发生。例如,我可能会在 effectEnded 触发某些东西的地方运行效果,或者缓慢的 Web 服务请求可能会超时并导致错误弹出。

由于垃圾收集器的工作方式 - 有时该对象对象会更快地被杀死,而其他时候则更晚。一旦某个部分关闭,我会尽量减少发生的坏事。

我想出了以下可能的解决方案。想知道有没有更好的。

  • 有一个设置为 true 的 _disposed 属性。在任何可能有不良行为的事件处理程序中(在该部分关闭后)我只想说if (_disposed) { return; }.
  • 可能还需要实现“IDisposable”接口,例如在 .NET 中。

这真的是我唯一的选择吗 - 或者我可以以某种方式加快垃圾收集。如果效果仍在运行,垃圾收集甚至会发生吗?

我也很好奇是否应该将事物设置为 _null,尤其是计时器。或者,如果没有对它的引用,只需 stop() 一个计时器就足以让它被垃圾收集。

4

2 回答 2

1

http://gskinner.com/talks/resource-management/

this is grand skinner's talk about garbage collection. Around slide 32 he talks about his janitor system. you can read over then and then grab his source files.

also make sure you are familiar with his talk about flash 9's garbage collection: http://www.gskinner.com/blog/archives/2008/04/failure_to_unlo.html

specifically look at this part:

Work-Arounds and Strategies There are four main things you can do to address these issues now:

  1. Make sure that you are always removing timer and enterframe event listeners in content you may want to load into a larger application. Also, try to avoid stage listeners where possible, and remove them immediately when you are done with them.

  2. Expose a standard API in your SWFs that allows other SWFs to tell it to clean up and stop executing. This way, the loading application can call this method (within a try/catch block) before it unloads any content. I would suggest a .halt() method, backed by a listener for a "halt" event through sharedEvents.

  3. You can load content SWFs from a subdomain. This will place it into a security sandbox implicitly.

  4. Load content into a div layered over your main application. This isn't a great option, but it addresses almost all of the issues.

于 2008-10-24T17:51:19.830 回答
0

您可以在 hideSection() 方法中删除所有活动的事件侦听器。

removeEventListener(this, listenerFunction, eventType);

如果您添加了带有弱引用的事件侦听器,并且没有其他对它的引用,那么侦听器的目标应该被垃圾回收。

于 2008-10-19T14:25:06.267 回答