Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one tell if an IDisposable object reference is disposed?

Is there a method, or some other light-weight way, to check if a reference is to a disposed object?

P.S. - This is just a curiousity (sleep well, not in production code). Yes, I know I can catch the ObjectDisposedException upon trying to access a member of the object.

like image 551
Neil C. Obremski Avatar asked Oct 10 '08 16:10

Neil C. Obremski


People also ask

How do you check if an object is disposed or not C#?

Notice the check on _disposed . If you were to call a Dispose method implementing this pattern, you could call Dispose as many times as you wanted without hitting exceptions.

How do you Dispose of IDisposable?

If you don't use using , then it's up to you (the calling code) to dispose of your object by explicitely calling Dispose().

What happens if you dont Dispose IDisposable?

IDisposable is usually used when a class has some expensive or unmanaged resources allocated which need to be released after their usage. Not disposing an object can lead to memory leaks.

What is IDisposable interface in C implement the Dispose method?

The Dispose method is automatically called when a using statement is used. All the objects that can implement the IDisposable interface can implement the using statement. You can use the ildasm.exe tool to check how the Dispose method is called internally when you use a using statement.


2 Answers

No - default implementation of IDisposable pattern does not support it

like image 103
Dandikas Avatar answered Oct 20 '22 00:10

Dandikas


System.Windows.Forms.Control has an IsDisposed property which is set to true after Dispose() is called. In your own IDisposable objects, you can easily create a similar property.

like image 31
Ryan Lundy Avatar answered Oct 19 '22 22:10

Ryan Lundy