gpt4 book ai didi

c# - 为什么在 C# 中没有引用计数 + 垃圾收集?

转载 作者:IT王子 更新时间:2023-10-29 03:47:13 27 4
gpt4 key购买 nike

我有 C++ 背景,使用 C# 已有大约一年的时间。像许多其他人一样,我对为什么确定性资源管理没有内置到语言中感到困惑。我们有处置模式,而不是确定性的析构函数。 People start to wonder通过他们的代码传播 IDisposable 癌症是否值得付出努力。

在我偏爱 C++ 的大脑中,使用带有确定性析构函数的引用计数智能指针似乎是垃圾收集器的重要一步,垃圾收集器要求您实现 IDisposable 并调用 dispose 来清理非内存资源。不可否认,我不是很聪明……所以我问这个纯粹是为了更好地理解为什么事情是这样的。

如果 C# 被修改为:

对象是引用计数的。当对象的引用计数变为零时,将对该对象确定性地调用资源清理方法,然后将该对象标记为垃圾收集。垃圾收集发生在未来某个不确定的时间,此时内存被回收。在这种情况下,您不必实现 IDisposable 或记住调用 Dispose。如果有非内存资源需要释放,就实现资源清理功能即可。

  • 为什么这是个坏主意?
  • 这会破坏垃圾收集器的目的吗?
  • 实现这样的事情是否可行?

编辑:从目前的评论来看,这是个坏主意,因为

  1. 没有引用计数的 GC 更快
  2. 处理对象图中循环的问题

我认为第一个是有效的,但第二个使用弱引用很容易处理。

速度优化是否超过了您的缺点:

  1. 可能无法及时释放非内存资源
  2. 可能过早释放非内存资源

如果您的资源清理机制是确定性的并且内置于语言中,您就可以消除这些可能性。

最佳答案

Brad Abrams 发布 an e-mail from Brian Harry在开发 .Net 框架期间编写。它详细说明了未使用引用计数的许多原因,即使早期的优先事项之一是与使用引用计数的 VB6 保持语义等价。它研究了一些可能性,例如计算某些类型的引用而不计算其他类型(IRefCounted!),或计算特定实例的引用,以及为什么这些解决方案都不被认为是可接受的。

Because [the issue of resourcemanagement and deterministicfinalization] is such asensitive topic I am going to try tobe as precise and complete in myexplanation as I can. I apologize forthe length of the mail. The first 90%of this mail is trying to convince youthat the problem really is hard. Inthat last part, I'll talk about thingswe are trying to do but you need thefirst part to understand why we arelooking at these options.

...

We initially started with theassumption that the solution wouldtake the form of automatic refcounting (so the programmer couldn'tforget) plus some other stuff todetect and handle cyclesautomatically. ...we ultimately concluded thatthis was not going to work in thegeneral case.

...

In summary:

  • We feel that it is very important to solve the cycle problemwithout forcing programmers tounderstand, track down and designaround these complex data structureproblems.
  • We want to make sure we have a high performance (both speed andworking set) system and our analysisshows that using reference countingfor every single object in the systemwill not allow us to achieve thisgoal.
  • For a variety of reasons, including composition and castingissues, there is no simple transparentsolution to having just those objectsthat need it be ref counted.
  • We chose not to select a solution that provides deterministicfinalization for a singlelanguage/context because it inhibitsinterop with other languages andcauses bifurcation of class librariesby creating language specificversions.

关于c# - 为什么在 C# 中没有引用计数 + 垃圾收集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/867114/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com