读书人

小弟我在Dispose里面调用了GC.Collect

发布时间: 2013-09-25 11:02:58 作者: rapoo

我在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楼所讲的原因无关。
[解决办法]
引用:
Quote: 引用:

1楼版主和2楼显然没理解lz的意思。
关键是那个dispose方法里没有把对象设为null,并且不满足obj被回收的条件。

我测试了一下,obj在using外声明没有问题,只要是在using当中被指定一次就行了。
我修改了一下代码,在Program对象中使用另一个叫做IFun的com对象,在Dispose里面设置为null.
这次在using以后,对象的Dispose就被调用了,证明using的对象声明可以在using之外。我的理解对吗?

using ATLProject3Lib;
namespace cs_ConsoleApplication1
{
class Program : IDisposable
{
public void Dispose()
{
f = null;
}
public int i = 2;
public IFun f;
public Program()
{
f = new Fun();
}
static void Main(string[] args)


{
Program obj = new Program();
using (obj)
{
Console.WriteLine(obj.f.Add(2,3));
}
Console.WriteLine(obj.f.Add(2,9));//这一句就有空指针错误了
}
}
}



Dispose是释放非托管资源的地方,托管资源不需要在这里设置成NULL.

读书人网 >C#

热点推荐