How do I know if an IDisposable interface object has called Dispose?
3 answers
If inheriting is not an option, then nothing. IDisposable is not some kind of clever system thing. It is just an interface with one method.
Accordingly, calling Dispose is just a method call. Similarly, some IMyInterface.MyMethod() called. No special events occur.
- I suspected it. But hoping for the best, thanks. - Dmitry Chistik
Probably implement the Dispose method in it so that it triggers some event. In general, some strange idea.
- Object is not mine, inheritance is not an option. This decision is known to me. - Dmitry Chistik
In the book "Deploying dependencies in .NET" by Mark Siman , a method called "Interception" is given.
So, we have the main class ClassA :
class ClassA : IDisposable { public void Do() { Console.WriteLine("Do something"); } public void Dispose() { Console.WriteLine("ClassA.Dispose"); } } We use it accordingly:
class Program { static void Main(string[] args) { ClassA a = new ClassA(); try { a.Do(); } finally { if (a != null) a.Dispose(); } } } The output will be:
Do something
ClassA.Dispose
Now, to add code that will be executed before or after the Dispose method, we add a mediator class:
class ClassB : IDisposable { private readonly IDisposable _obj; public ClassB(IDisposable obj) { if (obj == null) throw new ArgumentNullException("obj"); _obj = obj; } public void Dispose() { Console.WriteLine("Befor ClassA.Dispose"); _obj.Dispose(); Console.WriteLine("After ClassA.Dispose"); } } Usage will be:
class Program { static void Main(string[] args) { ClassA a = new ClassA(); ClassB b = new ClassB(a); try { a.Do(); } finally { if (b != null) b.Dispose(); } } } Accordingly, the output will be:
Do something
Befor ClassA.Dispose
ClassA.Dispose
After ClassA.Dispose
Thus, using the "Interception" you can add code that will be executed before or after performing the Dispose method, which is equivalent to the implementation of an event inside the class, with the exception of access to internal variables (but if necessary, they can be reached).
- The solution is interesting. But unfortunately I can not use it. I had to write my class and forcibly trigger events with the object's Disopose = ( - Dmitry Chistik