.net - 共享变量和垃圾收集

标签 .net vb.net garbage-collection

我一直在阅读 .NET 中的垃圾收集,希望得到一些澄清。因此,据我所知,如果我声明一个公共(public)共享类变量,GC 将永远不会摆脱它。它是否正确?

另外,私有(private)变量呢?举个例子:

public class myClass
    private shared myString As String

    public sub ChangeString(newString As String)
        myString = newString
    end sub
end class

如果没有类的实例,共享变量现在会被 GC 吗?如果我将 ChangeString 更改为共享子会怎样?

最佳答案

So, as I understand it if I declare a public shared class variable, the GC will never get rid of it. Is this correct?



几乎。 GC 不会清理共享变量引用的字符串。

但是,如果您调用 ChangeString使用新字符串,myString 指向的字符串将不再受此引用的影响,并且可能有资格获得 GC。但是,新字符串(由 newString 引用)现在将成为 myString 的根。变量,防止它被垃圾收集。

Would the shared variable now get GCed if there were no instances of the class?



不,共享变量是对象的根,因为它属于类的“类型”,而不是任何实例。

And what if I alter ChangeString to be a shared sub?



这将完全没有效果。

关于.net - 共享变量和垃圾收集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9382658/

相关文章:

vb.net - VS 2010 : How can I change the order of the Project Properties>Settings?

asp.net - 如何修复 "' ddlAssignedTo' 的 SelectedValue 无效,因为它不存在于项目列表中

python GC - 引用计数仅在 gc.collect() 时有效?

java - 为什么当我增加新时代内存时,Minor GC 时间会增加

.net - 什么是最好、最简单的 ajax 文件 uploader ?

c# - 等价于 ContinueWith(delegate, CancellationToken) with await continuation

c# - 是否可以区分具有相同完全限定名称的类型?

c# - 检查 WINWORD.EXE 进程是否正在运行?

c# - EntityKey 和 ApplyPropertyChanges()

language-agnostic - 垃圾收集可以与显式内存管理共存吗?