GC.AddMemoryPressure() 如何知道要向哪个对象添加内存压力?

发布于 2024-12-29 10:15:58 字数 399 浏览 2 评论 0原文

我最近需要使用 GC.AddMemoryPressure 和它让我感到奇怪的是,它不接受添加内存压力的对象作为参数。我认为因为它与运行时紧密相关,所以有某种机制可以将 this 指针传递给该方法。我的问题有三个:

  1. this 指针如何传递给方法?
  2. 我注意到从静态方法调用它时没有抛出异常。在这种情况下会发生什么?
  3. 为什么其他 GC 方法(例如 GC.SupressFinalize 和 GC.ReRegisterForFinalize)采用对象参数,而该方法不需要该参数?

I recently had need to use GC.AddMemoryPressure and it struck me as strange that it doesn't accept the object to add memory pressure to as an argument. I assume because it's so closely tied to the runtime, there is some mechanism by which the this pointer gets passed to the method. My question is threefold:

  1. How does the this pointer get passed to the method?
  2. I notice no exception is thrown when calling it from a static method. What happens in this case?
  3. Why do other GC methods such as GC.SupressFinalize and GC.ReRegisterForFinalize take an object argument where this method doesn't need one?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

苯莒 2025-01-05 10:15:58

不,它没有与任何特定对象明确关联。假设在处理/完成时,同一个对象将消除该压力。来自文档

在最简单的使用模式中,托管对象在构造函数中分配非托管内存,并在 Dispose 或 Finalize 方法中释放它。分配非托管内存后调用AddMemoryPressure方法,释放非托管内存后调用RemoveMemoryPressure方法。

在更复杂的场景中,内存压力可能会随着时间的推移而变化 - 但仍然预计会与相关对象的合作有关。

No, it's not explicitly associated with any specific object. The assumption is that at disposal/finalize time, the same object will remove that pressure. From the docs:

In the simplest usage pattern, a managed object allocates unmanaged memory in the constructor and releases it in the Dispose or Finalize method. Call the AddMemoryPressure method after allocating the unmanaged memory, and call the RemoveMemoryPressure method after releasing it.

In more complicated scenarios, the memory pressure may change over time - but it's still expected to be with the co-operation of the object in question.

走野 2025-01-05 10:15:58

AddMemoryPressure 会比正常情况下更快地启动垃圾收集器。就这样。当实例被收集并且需要运行它的终结器时,抑制和 RegisterForFinialise 调用或不调用该类型的特定代码...

建议您阅读垃圾收集器伙伴,您可能会发现您不需要调用IncreaseMemoryPressure,或者调用它几乎同样可能会导致性能下降。

AddMemoryPressure kicks the garbage collector into life sooner than it would do normally. That's all. Suppress and RegisterForFinialise call or not specific code for that type when an instance gets collected and it's finaliser needs to be run...

Suggest you read up on the garbage collector mate, you might find that you didn't need to call IncreaseMemoryPressure, or almost just as likely calling it will cause a deteriation in performance.

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