在 C# 中,可以创建对对象的弱引用,如下所述:
WeakReference 类
在.net 中,一些类还实现了 IDisposable 接口。调用此接口的 Dispose 方法可以手动处置当前持有的任何托管或非托管资源。一个示例可能是位图对象或类。
如果我将一个实现了 IDisposable 的对象分配给弱引用,那么如果弱引用收集了该对象,Dispose 会被调用吗?
In C# it is possible to create weak references to objects as described here:
WeakReference Class
In .net some classes also implement the IDisposable interface. Calling the Dispose method of this interface is performed to manually dispose of any managed or unmanaged resources currently being held onto. An example might be a Bitmap object or class.
If I assign an object that implements IDisposable to a weak reference, will Dispose be called if the weak reference collects the object?
发布评论
评论(4)
一般来说,答案确实是否定的。
但是,正确实现的类使用 IDisposable rel="noreferrer">IDisposable 模式(希望所有 .NET 类都这样做)。还将实现当对象被垃圾收集时调用的终结器,并且在终结器内,它将调用
Dispose
。因此,对于IDisposable
的所有正确实现,都会调用Dispose
方法。(注意:Fernando 的反例没有正确实现
IDisposable
)In general, the answer is indeed No.
However, a properly implemented class that implements
IDisposable
using the IDisposable pattern (hopefuly all .NET classes do this). Would also implement finalizer which is called when the object is garbage collected and inside the finalizer, it would callDispose
. So, for all proper implementations ofIDisposable
, theDispose
method will be called.(Note: the counter-example by Fernando is not implementing
IDisposable
properly)GC 永远不会调用 Dispose。 Dispose 必须由用户代码调用。
GC does not ever call Dispose. Dispose must be called by user code.
不,就这么简单;)
No. Simple like that ;)
否。检查此测试:
输出为:
如您所见,执行从未命中
Dispose
方法。No. Check this test:
The output is:
As you can see, the execution never hits the
Dispose
method.