通过将新值[]分配给填充数组,是否会导致内存泄漏

时间:2015-11-19 09:17:34

标签: c# arrays memory-leaks

我有一个或多或少像hastable一样的数组: 基于索引,值将放在数组中,因此数组的某些索引将包含值,其他索引可能不会或不会。 我有两段代码:

public void register( int index, string value )
{
    _array[index] = value;
}
public void unregisterAll( )
{
    /*
    is this going to cause a memory leak when some of the values
    are filled int the above function?
    */
    _array = new string[12];
}

1 个答案:

答案 0 :(得分:7)

C#使用垃圾收集器。如果某个对象不再被引用,那么(在一段时间后)会自动释放。

执行unregisterAll()

时会发生这种情况(从垃圾收集器(GC)的角度来看)
object_array`1: referenced by _array
// execute unregisterAll();
create object_array`2 and let _array reference it
// Some time later when the GC runs
object_array`1: not referenced
object_array`2: referenced by _array
// Some time later, when the GC decided to collect
collect object__array`1

请注意,这并不意味着您不能在C#中发生内存泄漏。有些对象使用需要手动处理的非托管资源(它们实现了接口IDisposable,您可以通过在使用块中对其进行范围设置来自动处理:

using(IDisposable disposable = new ...)
{
    // use it
} // when leaving this scope disposable.Dispose() is automatically called

或者您可以通过调用Dispose()手动处理它们。