Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weak References and Disposable objects

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?

like image 953
Steve Sheldon Avatar asked May 15 '10 18:05

Steve Sheldon


1 Answers

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 call Dispose. So, for all proper implementations of IDisposable, the Dispose method will be called.

(Note: the counter-example by Fernando is not implementing IDisposable properly)

like image 78
Tomas Petricek Avatar answered Sep 22 '22 05:09

Tomas Petricek