我在Dispose里面调用了GC.Collect(),为什么对象还存在?
我定义从IDisposable继承的类,Dispose函数里面调用了GC.Collect。但是我发现using它之后,该object仍然存在,似乎并么有被销毁。这是为什么?
namespace cs_ConsoleApplication1
{
class Program : IDisposable
{
public void Dispose()
{
GC.Collect();
}
public int i = 2;
static void Main(string[] args)
{
Program obj = new Program();
using (obj)//我期待的是using的范围之外,obj就应该被GC回收了。
{
Console.WriteLine(obj.i);
}
Console.WriteLine(obj.i);//没有问题,obj仍然存在
}
}
}
求解释!
[解决办法]
你的obj在using外呢,都没搞明白using怎么用
using (DataTable dt = new DataTable())
{
}
[解决办法]
你obj的初始化在using之后外了,你应该这样使用:
using(Program obj =new Program())
{}
[解决办法]
to 楼上 看来是我理解错了
to 楼主
GC.Collect();只是强制执行垃圾回收 进行未被使用资源释放
即使你这样写
static void Main(string[] args)
{
Program objtest;
using (Program obj = new Program())//我期待的是using的范围之外,obj就应该被GC回收了。
{
objtest = obj;
Console.WriteLine(obj.i);
}
Console.WriteLine(objtest.i);//没有问题,obj仍然存在
Console.ReadLine();
}
new Program()对象也不会被释放
因为objtest = obj的存在导致new Program()对象仍在objtest存在的地方 被使用
此处似乎明显区别于C++的 free()
[解决办法]
求权威人士指正
[解决办法]
关键看你的dispose方法里是怎么写的,你把它设为null了就自然引用不到了,这个我先前已经说了。执行using块后都会调用dispose方法,跟1楼所讲的原因无关。
[解决办法]
Dispose是释放非托管资源的地方,托管资源不需要在这里设置成NULL.