c# - 在 C# 中释放内存的正确方法是什么

标签 c# memory memory-leaks

我在 C# 中有一个计时器,它在它的方法中执行一些代码。在代码中我使用了几个临时对象。

  1. 如果我在方法中有类似 Foo o = new Foo(); 的东西,这是否意味着每次计时器滴答作响时,我都会创建一个新对象和一个新对象引用该对象?

  2. 如果我有 string foo = null 然后我只是在 foo 中放了一些临时的东西,它和上面一样吗?

  3. 垃圾收集器是否曾经删除过对象并且引用或对象会不断创建并保留在内存中?

  4. 如果我只是声明 Foo o; 而没有将它指向任何实例,那不是在方法结束时释放了吗?

  5. 如果我想确保删除所有内容,最好的方法是:

    • 在方法中使用 using 语句
    • 最后调用 dispose 方法
    • 通过将 Foo o; 放在计时器的方法之外,并在内部进行赋值 o = new Foo(),这样指向对象的指针就会在方法结束,垃圾收集器将删除该对象。

最佳答案

1.If I have something like Foo o = new Foo(); inside the method, does that mean that each time the timer ticks, I'm creating a new object and a new reference to that object?

是的。

2.If I have string foo = null and then I just put something temporal in foo, is it the same as above?

如果你问行为是否相同,那么是的。

3.Does the garbage collector ever delete the object and the reference or objects are continually created and stay in memory?

这些对象使用的内存肯定是在引用被认为未使用后收集的。

4.If I just declare Foo o; and not point it to any instance, isn't that disposed when the method ends?

不,因为没有创建对象,所以没有要收集的对象(dispose 不是正确的词)。

5.If I want to ensure that everything is deleted, what is the best way of doing it

如果对象的类实现了IDisposable,那么你肯定想尽快贪婪地调用Disposeusing 关键字使这更容易,因为它以异常安全的方式自动调用 Dispose

除了停止使用该对象之外,您实际上不需要做任何其他事情。如果引用是一个局部变量,那么当它超出范围时,它将有资格被收集。1 如果它是一个类级别的变量,那么您可能需要分配 null使其在包含类符合条件之前使其符合条件。


1这在技术上是不正确的(或者至少有点误导)。一个对象在超出范围之前就可以被收集。 CLR 被优化为在检测到不再使用引用时收集内存。在极端情况下,即使其中一个方法仍在执行,CLR 也可以收集对象!

更新:

这里是一个例子,展示了 GC 将收集对象,即使它们可能仍在范围内。您必须编译发布版本并在调试器之外运行它。

static void Main(string[] args)
{
    Console.WriteLine("Before allocation");
    var bo = new BigObject();
    Console.WriteLine("After allocation");
    bo.SomeMethod();
    Console.ReadLine();
    // The object is technically in-scope here which means it must still be rooted.
}

private class BigObject
{
    private byte[] LotsOfMemory = new byte[Int32.MaxValue / 4];

    public BigObject()
    {
        Console.WriteLine("BigObject()");
    }

    ~BigObject()
    {
        Console.WriteLine("~BigObject()");
    }

    public void SomeMethod()
    {
        Console.WriteLine("Begin SomeMethod");
        GC.Collect();
        GC.WaitForPendingFinalizers();
        Console.WriteLine("End SomeMethod");
    }
}

在我的机器上运行终结器,而 SomeMethod 仍在执行!

关于c# - 在 C# 中释放内存的正确方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6066200/

相关文章:

C++ 函数调用后无关指针发生变化

linux - 为什么 perl 编译后的代码需要更多的内存?

java - 静态上下文保存在 Application 类中并在单例 Toast 构建器中使用,这是否会造成内存泄漏?

c# - C# 中的 SIFT 实现

c# - AsyncLocal 与 ASP.NET Core Controller /ServiceProviderScope

c++ - 我怎样才能像使用 wistream 从文件中读取一样从内存中读取?

javascript - 关闭内存泄漏并修复

memory-leaks - Sitecore实例崩溃-分析内存转储的最佳工具是什么?

c# - 将 Reflection.Emit 转换为 Roslyn

c# - 找不到 StructureMap 可插入类型或命名空间