gpt4 book ai didi

c# - 我会通过将新值 [] 分配给填充数组来导致内存泄漏吗

转载 作者:行者123 更新时间:2023-11-30 19:56:27 24 4
gpt4 key购买 nike

我有一个或多或少像 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];
}

最佳答案

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# 中发生内存泄漏。一些对象使用需要手动处理的非托管资源(它们实现了接口(interface) IDisposable,您可以通过将其限定在 using block 中来自动处理该接口(interface):

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

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

关于c# - 我会通过将新值 [] 分配给填充数组来导致内存泄漏吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33799604/

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