1 回答

TA贡献1875条经验 获得超3个赞
在 C# 中,垃圾收集器将管理所有对象并释放不再有任何引用的任何对象的内存。
使用您的示例:
RandomObject x;
// A RandomObject reference is defined.
x = new RandomObject(argX, argY);
// Memory is allocated, a new RandomObject object is created in that memory location,
// and "x" references that new object.
x = new RandomObject(argZ, argV);
// Memory is allocated, a new RandomObject object is created in that memory location,
// and "x" references that new object. The first RandomObject object no longer has
// any references to it and will eventually be cleaned up by the garbage collector.
非托管资源
尽管 C# 中的所有对象都是托管的,但仍有“非托管资源”,例如打开的文件或打开的连接。当具有非托管资源的对象超出范围时,它将被垃圾回收,但垃圾回收器不会释放这些非托管资源。这些对象通常实现IDisposable允许您在清理资源之前对其进行处置。
例如,StreamWriter类中有一个非托管资源,它打开一个文件并写入它。
以下是未能释放非托管资源的示例:
// This will write "hello1" to a file called "test.txt".
System.IO.StreamWriter sw1 = new System.IO.StreamWriter("test.txt");
sw1.WriteLine("hello1");
// This will throw a System.IO.IOException because "test.txt" is still locked by
// the first StreamWriter.
System.IO.StreamWriter sw2 = new System.IO.StreamWriter("test.txt");
sw2.WriteLine("hello2");
要正确释放文件,您必须执行以下操作:
// This will write "hello1" to a file called "test.txt" and then release "test.txt".
System.IO.StreamWriter sw1 = new System.IO.StreamWriter("test.txt");
sw1.WriteLine("hello1");
sw1.Dispose();
// This will write "hello2" to a file called "test.txt" and then release "test.txt".
System.IO.StreamWriter sw2 = new System.IO.StreamWriter("test.txt");
sw2.WriteLine("hello2");
sw2.Dispose();
幸运的是,实现的对象IDisposable可以在using语句中创建,然后当它超出范围Dispose()时将自动调用它。这比手动调用 Dispose(如前面的示例)要好,因为如果在 using 块中有任何意外退出点,您可以放心您的资源已被释放。
using (System.IO.StreamWriter sw1 = new System.IO.StreamWriter("test.txt"))
{
sw1.WriteLine("hello1");
}
using (System.IO.StreamWriter sw2 = new System.IO.StreamWriter("test.txt"))
{
sw2.WriteLine("hello2");
}
- 1 回答
- 0 关注
- 195 浏览
添加回答
举报