考虑以下代码:
namespace DisposeTest
{
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Calling Test");
Test();
Console.WriteLine("Call to Test done");
}
static void Test()
{
DisposeImplementation di = new DisposeImplementation();
}
}
internal class DisposeImplementation : IDisposable
{
~DisposeImplementation()
{
Console.WriteLine("~ in DisposeImplementation instance called");
}
public void Dispose()
{
Console.WriteLine("Dispose in DisposeImplementation instance called");
}
}
}
Dispose方法从来没有被调用,即使我在Test()调用之后放置了一个等待循环。所以这相当糟糕。我想编写一个简单易用的类,以确保每个可能的资源都得到清理。我不想把这个责任交给我的类的用户。可能的解决方案:使用using,或者自己调用Dispose(基本上是一样的)。我能强制用户使用using吗?或者我能强制调用Dispose吗?
在Test()之后调用GC.Collect()也不起作用。
将di设置为null也不会触发Dispose。析构函数确实有效,因此当对象退出Test()时,它会被析构。
好的,伙计们,现在清楚了!
谢谢大家的答案!我会在评论中添加一个警告!
using
语句包装可处理对象*”或类似的内容… - James