我尝试使用以下代码
[DllImport("Core.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr CreateNode();
[DllImport("Core.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
public static extern void ReleaseNode(IntPtr handle);
class Node
{
IntPtr nativePtr;
public int id;
public Node(int i)
{
nativePtr = CreateNode();
id = i;
Debug.WriteLine("Constructed " + id);
}
~Node()
{
ReleaseNode(nativePtr);
Debug.WriteLine("Destructed " + id);
}
}
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
{
Node n = new Node(i);
} //this scope
}
}
Node
在循环内创建的类的每个对象for
在离开 for 循环范围后都不会破坏(注释为“此范围”)。只有在 Main 方法的范围结束时才会调用它。当 for 循环范围结束时,是否可以自动调用 ~Node?
在执行上述代码时,我在调试窗口中得到以下信息。
Constructed 0
Constructed 1
Constructed 2
Constructed 3
Constructed 4
Constructed 5
Constructed 6
Constructed 7
Constructed 8
Constructed 9
Destructed 9
Destructed 0
Destructed 8
Destructed 7
Destructed 6
Destructed 5
Destructed 4
Destructed 3
Destructed 2
Destructed 1
这表明首先构造的对象最后被破坏了。如果发生这种情况,当我在循环中运行数千个项目时会发生什么?它会消耗我所有的记忆吗?
我怎样才能完美地释放我的非托管资源?