Reason for Using IDisposable Interface - c#

We all know that IDisposable interface is using for disposing unmanaged resources.
I have a class which contains following code. here i have implemented the Dispose method from IDisposable interface.
class ClassA:IDisposable
{
public ClassA()
{
Console.WriteLine("ClassBeingTested: Constructor");
}
private bool disposed = false;
Image img = null;
public Image Image
{
get { return img; }
}
~ClassA()
{
Console.WriteLine("ClassBeingTested: Destructor");
// call Dispose with false. Since we're in the
// destructor call, the managed resources will be
// disposed of anyways.
Dispose(false);
}
public void Dispose()
{
Console.WriteLine("ClassBeingTested: Dispose");
// dispose of the managed and unmanaged resources
Dispose(true);
// tell the GC that the Finalize process no longer needs
// to be run for this object.
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposeManagedResources)
{
// process only if mananged and unmanaged resources have
// not been disposed of.
if (!this.disposed)
{
Console.WriteLine("ClassBeingTested: Resources not disposed");
if (disposeManagedResources)
{
Console.WriteLine("ClassBeingTested: Disposing managed resources");
// dispose managed resources
if (img != null)
{
img.Dispose();
img = null;
}
}
// dispose unmanaged resources
Console.WriteLine("ClassBeingTested: Disposing unmanaged resouces");
disposed = true;
}
else
{
Console.WriteLine("ClassBeingTested: Resources already disposed");
}
}
// loading an image
public void LoadImage(string file)
{
Console.WriteLine("ClassBeingTested: LoadImage");
img = Image.FromFile(file);
}
}
What my doubt is why i need to implement the Dispose method from IDisposable interface?. Instead of that i can create my own Dispose method in my class without inheriting from IDisposable interface which i have given below.
for the class below i haven't inherited my class from IDisposable interface. instead of that i created my own dispose method. this also works fine.
class ClassA
{
public ClassA()
{
Console.WriteLine("ClassBeingTested: Constructor");
}
private bool disposed = false;
Image img = null;
public Image Image
{
get { return img; }
}
~ClassA()
{
Console.WriteLine("ClassBeingTested: Destructor");
// call Dispose with false. Since we're in the
// destructor call, the managed resources will be
// disposed of anyways.
Dispose(false);
}
public void Dispose()
{
Console.WriteLine("ClassBeingTested: Dispose");
// dispose of the managed and unmanaged resources
Dispose(true);
// tell the GC that the Finalize process no longer needs
// to be run for this object.
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposeManagedResources)
{
// process only if mananged and unmanaged resources have
// not been disposed of.
if (!this.disposed)
{
Console.WriteLine("ClassBeingTested: Resources not disposed");
if (disposeManagedResources)
{
Console.WriteLine("ClassBeingTested: Disposing managed resources");
// dispose managed resources
if (img != null)
{
img.Dispose();
img = null;
}
}
// dispose unmanaged resources
Console.WriteLine("ClassBeingTested: Disposing unmanaged resouces");
disposed = true;
}
else
{
Console.WriteLine("ClassBeingTested: Resources already disposed");
}
}
// loading an image
public void LoadImage(string file)
{
Console.WriteLine("ClassBeingTested: LoadImage");
img = Image.FromFile(file);
}
}
So can any one tel me tat the reason behind of implementing dispose method from IDisposable interface.

When you implement IDisposable, you can use using for exception-safe disposing.

Two reasons:
Implementing IDisposable expresses intent (this should be disposed) in a conventional manner. It's easy to spot that you should dispose of a resource if it implements IDisposable, whereas relying on other developers to read the documentation carefully is more likely to lead to errors.
That convention is used by the using statement. You should be able to write:
using (ClassA foo = new ClassA())
{
...
}
... but unless you implement IDisposable, you can't.
(Personally I wouldn't include a finalizer, by the way... that's usually only for directly held unmanaged resources; here you should rely on the Image finalizer.)

Although implementing your own dispose method will suffice for any explicit call made to that method but when,after implementig Idispobale, you use a using statement, the built in .Net functionality will invoke your dispose method for you so your code can look like this;
using (ClassA foo = new ClassA())
{
...
}
rather than this
using (ClassA foo = new ClassA())
{
....
foo.Dispose();
}

When you implement IDisposable interface you can use your class in using block, like this:
...
using(var classA = new ClassA())
{
do some stuff
}
after it your Dispose method will be invoked.
It is quite useful.

IDisosable is very useful. For example working with Database connections. It requires all of its implementations to have Dispose method.
It is very useful for working with unmanaged resources, where you have to release them as for the Database connections above, because Garbage Collector is working on managed code (it releases objects where they are not in use anymore), but for unmanaged as C++ application or library (without CLR), it has no idea what is going there. By using its disposable method you say you have finished your work with such a resource and it is being released (freeing memory).
Example (example class and usage):
class Database : IDisposable
{
private SqlConnection _conn;
public Database(string conn_str)
{
// Doing the connectivity
}
public Dataset Read(string sql)
{
SqlCommand cmd = new SqlCommand();
Dataset result = null;
// etc...
return result;
}
public Dispose()
{
_conn.Close();
}
}
using(Database db = new Database(conn_string))
{
Dataset ds = db.Read("SELECT something FROM table");
}
The this approach is very useful. In this statement you init your IDisposable and at the end of statement (not needed to call db.Dispose()) its Dispose() is called and the resources are freed. In this case unmanaged resource may be the .NET SQL Driver, you can use MySQL library, etc.

Three "unwritten" parts of the contract for .net objects are:
If a class implements IDisposable, then once the instance is no longer needed, calling IDisposable.Dispose() on it and abandoning it should take care of all necessary cleanup, regardless of the type of object.
If an object does not implement IDisposable, it may be safely abandoned any time it is no longer needed, without requiring any cleanup.
An object which constructs an instance of a class which implements IDisposable is responsible for ensuring that IDisposable gets called, either by doing it itself when it is done with the object, or ensuring that the reference gets handed off to some other object which will carry out the responsibility.
This is in general a very useful pattern. While there are some rare occasions when it will be impossible for a class to properly implement IDisposable (most commonly because the class exists to expose a complex resource whose cleanup semantics are understood by the user of the class, but not by the class itself), it's very useful to have a unified means of cleanup when things like exceptions occur.

Related

Why IDisposable interface? [duplicate]

This question already has answers here:
Proper use of the IDisposable interface
(20 answers)
Closed 2 years ago.
I've gone through many article which says the purpose of IDisposable is to close the unmanaged objects like DB connections and Third party reports.But my question is why should I define Dispose method if I can handle the unmanaged objects in my methods without defining Dispose() method?
For an example,
class Report : IDisposable
{
public void GenerateReport()
{
Report rpt=new Report() //unmanaged object created
rpt.Dispose(); // Disposing the unmanaged object
}
private void Dispose()
{
//not sure why this block is needed
}
}
Is my understanding correct?
You're correct that you wouldn't need the implement IDisposable in your example. The example where you would is if you're keeping a long lived object for the life of the class you've written. So say you had this:
public class Report : IDisposable
{
private Stream _reportStream; // This variable lives a long time.
public void WriteToStream(byte[] data)
{
_reportStream.Write(data, 0, data.Length);
}
public void Dispose()
{
_reportStream?.Dispose();
}
}
This is a fairly simple example, but it shows that _reportStream lives for the length of the class and needs to get cleaned up and garbage collected at the same time as the class. There's nothing stopping you from creating a public method called CleanupObject() to do the same thing, but then people can't use a using block to have the Runtime call the Dispose() automatically:
using (var myReport = new Report())
{
// do a bunch of things with myReport;
} // Here the runtime will call myReport.Dispose() for you.
// myReport isn't accessible from here, as it was declared in the using block
The class that implements the IDisposable interface can be used in the using block. A big plus of this solution is that after leaving the block the Dispose method will be automatically called on the object created in this area. That way, we can only use classes that implement the IDisposable interface.
//example :
using(var dClean= new DisposableClean())
{
//after leaving this using dClean will be automatically destroyed
}
The object that you've created needs to expose some method, not necessary named Dispose(). You could also call it Clean(). Dispose() is the conventional name.
Garbage Collector(GC), available throughout the .Net framwork, works well enough to be easily forgotten. However, it is worth learning to work with him well and use his possibilities. For this purpose, the correct implementation of the IDisposable interface is necessary, the basic form of which is sometimes insufficient if we consider the proper release of managed and unmanaged resources.
This is extanded version which can be very useful in this case.
In a way an answer to you question:
public class DisposableExtended: IDisposable
{
private bool isDisposed = false;
public void Dispose ()
{
this.Dispose (true);
GC.SupressFinalize (this);
}
protected void Dispose (bool disposing)
{
if (! this.isDisposed)
{
if (disposing)
{
// here we release managed resources (standard classes)
}
// here we release unmanaged resources (e.g. streams, etc..)
{
}
}
this .isDisposed = true;
}
~ DisposableExtended ()
{
this.Dispose (false);
}
Yes, you can define your own way to release resources but many existing code use this way. If you share your code to people, remember to tell them to dispose in your way.
One "profit" of implementing IDisposable is that you can call Dispose indirectly by use a language construct such as using.
For example:
using(Stream s = File.OpenRead("HelloWorld.bin"))
{
//Do stuffs
}

Instance method call Dispose

Is correct that a public method calls the Dispose of IDisposable in the same class?
E.g.
public class Worker : IDisposable
{
public void Close()
{
SendCloseCommand();
Dispose();
}
public void Dispose()
{
////other resources release
}
private void SendCloseCommand()
{
}
}
Another thing about disposable pattern:
If the Close should be always called, is better that is called from the Dispose method or not?
If not, I should put the usage of the Worker class in a try/catch/finally everywhere, to call the Close. Right?
The correct design should instead be?
public class Worker : IDisposable
{
public void Close()
{
SendCloseCommand();
}
public void Dispose()
{
Close();
////other resources release
}
private void SendCloseCommand()
{
////other stuff
}
}
If you look at Microsoft implementation for StreamReader, Dispose gets called from Close,
public override void Close()
{
Dispose(true);
}
and also the implementation for Dispose closes the stream as well by calling Close of base Stream.
protected override void Dispose(bool disposing)
{
// Dispose of our resources if this StreamReader is closable.
// Note that Console.In should be left open.
try {
// Note that Stream.Close() can potentially throw here. So we need to
// ensure cleaning up internal resources, inside the finally block.
if (!LeaveOpen && disposing && (stream != null))
stream.Close();
}
finally {
if (!LeaveOpen && (stream != null)) {
stream = null;
encoding = null;
decoder = null;
byteBuffer = null;
charBuffer = null;
charPos = 0;
charLen = 0;
base.Dispose(disposing);
}
}
}
In your class implementation, I would call the Dispose from your Close method as you are doing in your first code snippet. In Dispose, I would check for Worker status, if it is not closed then close it using SendCloseCommand, and then release resources.
public void Dispose()
{
if(this.Status != Closed) // check if it is not already closed
{
SendCloseCommand();
}
////other resources release
}
This will ensure your resources disposal, even if your class is used with using statement, or if any one calls Close manually.
Just remember to check status of your Worker object, before issuing Close Command.
Microsoft has some suggestions about having a Close method on a class implementing IDisposable. It is part of the Dispose Pattern guidelines:
CONSIDER providing method Close(), in addition to the Dispose(), if close is standard terminology in the area.
When doing so, it is important that you make the Close implementation identical to Dispose and consider implementing the IDisposable.Dispose method explicitly.
public class Stream : IDisposable {
IDisposable.Dispose(){
Close();
}
public void Close(){
Dispose(true);
GC.SuppressFinalize(this);
}
}
So Microsofts suggestion is to hide Dispose and let it call Close to do the actual cleanup. Also, remember the guideline about multiple calls to Dispose:
DO allow the Dispose(bool) method to be called more than once. The method might choose to do nothing after the first call.
Following these guidelines makes your code consistent with the .NET library and you will avoid any confusion about if your class should be closed or disposed for proper cleanup.

how to ensure no memory leak in the following case

If a class has a property which contains unmanaged resources. How to make sure no memory leak when using the class
Class A
{
B {get; set;}
}
B contains unmanaged resources.
Implement IDisposable and clean up your unmanaged resources by calling Dispose(), preferably placing the call to Dispose in a finally statement so you clean up resources even in the case of an exception.
C# has a using keyword that you can employ to make sure that the Dispose method is called, even if an exception is thrown.
EDIT: Incorporated call to GC.SuppressFinalize and finalizer implementation per Ran's answer
class A : IDisposable
{
private bool _disposed;
~A()
{
this.Dispose(false);
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
// dispose managed resources
}
// clean up unmanaged resources
_disposed = true;
}
}
}
class Program
{
static void Main(string[] args)
{
using (var someInstance = new A())
{
// do some things with the class.
// once the using block completes, Dispose
// someInstance.Dispose() will automatically
// be called
}
}
}
Using IDisposable might not be enough, because it relies on the user remembering to call Dispose or to use using etc.
For a complete solution, combine IDisposable and a finalizer. Like this:
Edit: Made some corrections in the Dispose method based on SpeksETC's comment.
class MyClass : IDisposable
{
~MyClass()
{
Dispose(false);
}
public void Dispose()
{
GC.SupressFinalize();
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (!disposing)
{
// clear unmanaged resources here (can only be called once)
...
}
// dispose called explicitly by the user, clean up managed resources here
...
}
}
This ensures that native resources will always be cleared, even if the user forgets to call Dispose, while still allowing the user to clear the resources early.
The if inside the Dispose implementation is needed because if this class is being finalized, you may not call Dispose on your members because they may have been GC'ed already.
I think it is important to point out that B is a managed resource that only contains unmanaged resources.
Therefore, A should implement IDisposable and dispose of B in its Dispose() method, but does not need a finalizer since it doesn't have any unmanaged resources to clean up - the finalizer needs to be implemented within B itself. Even if you implemented a finalizer it would call a Dispose that looked like this:
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// dispose called explicitly by the user, clean up managed resources here
b.Dispose()
}
// no unmanaged resources to clean up so do nothing which makes Finalizer unneccesary
...
}
SpeksEtc is correct in that if B contains unmanaged resources then B should ensure there are no leaks not A.
But what are the unmanaged resources and would the SafeHandle class help? Then B would contain a SafeHandle which would contain the unmanaged resource and you wouldn't need to worry about it.

Proper way to dispose of Quartz.NET?

I am using Quartz.NET in an application. What is the proper way to dispose of Quartz.NET.
Right now I am just doing
if (_quartzScheduler != null)
{
_quartzScheduler = null;
}
Is that enough or should I implement a dispose or something in the jobType class?
Seth
scheduler.Shutdown(waitForJobsToComplete: true);
Of course, if you're not on C# 4.0 yet, named parameters don't work:
scheduler.Shutdown(true);
This is not a complete example but might get you on the right path. I would implement something like this:
class customSchedulerClass : IDisposable
{
private Component component = new Component();
private bool disposed = false;
public void scheduleSomeStuff()
{
//This is where you would implement the Quartz.net stuff
}
public void Dispose()
{
Dispose(true);
GC.SupressFinalize(this);
}
private void Dispose(bool disposing)
{
if(!this=disposed)
{
if(disposing)
{
component.dispose;
}
}
disposed = true;
}
}
Then with this you can do cool stuff like using statements:
public static void Main()
{
using (customSchedulerClass myScheduler = new customSchedulerClass())
{
c.scheduleSomeStuff();
}
console.WriteLine("Now that you're out of the using statement the resources have been disposed");
}
So basically by implementing you code while inheriting the functionality of IDisposable you can then us the using statement and when you're done it will cleanly dispose your resources and keep things nice and clean. (Disclaimer, again this is not a complete example, just to get you in the right direction).
The docs don't say anything about IScheduler implementing IDisposable. If you have custom job types that grab and hold resources (file locks, database connections), you can implement IDispoable and override Dispose() on your object to release resources.
Generally we don't need to set an object to null in order to dispose it off.
If an object contains unmanaged resources then it should implement IDisposable (and be called by all its clients).
You can refere this similar post.

Calling base.Dispose() automatically from derived classes

Edit - New Question
Ok lets rephrase the question more generically.
Using reflection, is there a way to dynamically call at runtime a base class method that you may be overriding. You cannot use the 'base' keyword at compile time because you cannot be sure it exists. At runtime I want to list my ancestors methods and call the ancestor methods.
I tried using GetMethods() and such but all they return are "pointers" to the most derived implementation of the method. Not an implementation on a base class.
Background
We are developing a system in C# 3.0 with a relatively big class hierarchy. Some of these classes, anywhere in the hierarchy, have resources that need to be
disposed of, those implement the IDisposable interface.
The Problem
Now, to facilitate maintenance and refactoring of the code I would like to find a way, for classes implementing IDisposable,
to "automatically" call base.Dispose(bDisposing) if any ancestors also implements IDisposable. This way, if some class higher up in the hierarchy starts implementing
or stops implementing IDisposable that will be taken care of automatically.
The issue is two folds.
First, finding if any ancestors implements IDisposable.
Second, calling base.Dispose(bDisposing) conditionally.
The first part, finding about ancestors implementing IDisposable, I have been able to deal with.
The second part is the tricky one. Despite all my
efforts, I haven't been able to call base.Dispose(bDisposing) from a derived class. All my attempts failed. They either caused
compilation errors or called the wrong Dispose() method, that is the most derived one, thus looping forever.
The main issue is that you cannot actually refer to base.Dispose() directly in your code if there is no such thing as an
ancestor implementing it (be reminded that there might have no ancestors yet implementing IDisposable, but I want the derived code to be ready when and if such
a thing happens in the future). That leave us with the Reflection mechanisms, but I did not find a proper way of doing it. Our code is quite filled with
advanced reflection techniques and I think I did not miss anything obvious there.
My Solution
My best shot yet was to have some conditional code using in commented code. Changing the IDisposable hierarchy would either break the build
(if no IDisposable ancestor exists) or throw an exception (if there are IDisposable ancestors but base.Dispose is not called).
Here is some code I am posting to show you what my Dispose(bDisposing) method looks like. I am putting this code at the end of all the Dispose()
methods throughout the hierarchy. Any new classes are created from templates that also includes this code.
public class MyOtherClassBase
{
// ...
}
public class MyDerivedClass : MyOtherClassBase, ICalibrable
{
private bool m_bDisposed = false;
~MyDerivedClass()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool bDisposing)
{
if (!m_bDisposed) {
if (bDisposing) {
// Dispose managed resources
}
// Dispose unmanaged resources
}
m_bDisposed = true;
Type baseType = typeof(MyDerivedClass).BaseType;
if (baseType != null) {
if (baseType.GetInterface("IDisposable") != null) {
// If you have no ancestors implementing base.Dispose(...), comment
// the following line AND uncomment the throw.
//
// This way, if any of your ancestors decide one day to implement
// IDisposable you will know about it right away and proceed to
// uncomment the base.Dispose(...) in addition to commenting the throw.
//base.Dispose(bDisposing);
throw new ApplicationException("Ancestor base.Dispose(...) not called - "
+ baseType.ToString());
}
}
}
}
So, I am asking is there a way to call base.Dispose() automatically/conditionally instead?
More Background
There is another mechanism in the application where all objects are registered with a main class. The class checks if they implement IDisposable.
If so, they are disposed of properly by the application. This avoids having the code using the classes to deal with
calling Dispose() all around by themselves. Thus, adding IDisposable to a class that has no ancestor history of IDisposable still works perfectly.
The standard pattern is for your base class to implement IDisposable and the non-virtual Dispose() method, and to implement a virtual Dispose(bool) method, which those classes which hold disposable resources must override. They should always call their base Dispose(bool) method, which will chain up to the top class in the hierarchy eventually. Only those classes which override it will be called, so the chain is usually quite short.
Finalizers, spelled ~Class in C#: Don't. Very few classes will need one, and it's very easy to accidentally keep large object graphs around, because the finalizers require at least two collections before the memory is released. On the first collection after the object is no longer referenced, it's put on a queue of finalizers to be run. These are run on a separate, dedicated thread which only runs finalizers (if it gets blocked, no more finalizers run and your memory usage explodes). Once the finalizer has run, the next collection that collects the appropriate generation will free the object and anything else it was referencing that isn't otherwise referenced. Unfortunately, because it survives the first collection, it will be placed into the older generation which is collected less frequently. For this reason, you should Dispose early and often.
Generally, you should implement a small resource wrapper class that only manages the resource lifetime and implement a finalizer on that class, plus IDisposable. The user of the class should then call Dispose on this when it is disposed. There shouldn't be a back-link to the user. That way, only the thing that actually needs finalization ends up on the finalization queue.
If you are going to need them anywhere in the hierarchy, the base class that implements IDisposable should implement the finalizer and call Dispose(bool), passing false as the parameter.
WARNING for Windows Mobile developers (VS2005 and 2008, .NET Compact Framework 2.0 and 3.5): many non-controls that you drop onto your designer surface, e.g. menu bars, timers, HardwareButtons, derive from System.ComponentModel.Component, which implements a finalizer. For desktop projects, Visual Studio adds the components to a System.ComponentModel.Container named components, which it generates code to Dispose when the form is Disposed - it in turn Disposes all the components that have been added. For the mobile projects, the code to Dispose components is generated, but dropping a component onto the surface does not generate the code to add it to components. You have to do this yourself in your constructor after calling InitializeComponent.
Personally, I think you might be better off handling this with something like FxCop. You should be able to write a rule that check so see if when an object is created that implements IDisposable that you use a using statement.
It seems a little dirty (to me) to automatically dispose an object.
There is not an "accepted" way of doing this. You really want to make your clean up logic (whether it runs inside of a Dispose or a finalizer) as simple as possible so it won't fail. Using reflection inside of a dispose (and especially a finalizer) is generally a bad idea.
As far as implementing finalizers, in general you don't need to. Finalizers add a cost to your object and are hard to write correctly as most of the assumptions you can normally make about the state of the object and the runtime are not valid.
See this article for more information on the Dispose pattern.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestDisposeInheritance
{
class Program
{
static void Main(string[] args)
{
classC c = new classC();
c.Dispose();
}
}
class classA: IDisposable
{
private bool m_bDisposed;
protected virtual void Dispose(bool bDisposing)
{
if (!m_bDisposed)
{
if (bDisposing)
{
// Dispose managed resources
Console.WriteLine("Dispose A");
}
// Dispose unmanaged resources
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
Console.WriteLine("Disposing A");
}
}
class classB : classA, IDisposable
{
private bool m_bDisposed;
public void Dispose()
{
Dispose(true);
base.Dispose();
GC.SuppressFinalize(this);
Console.WriteLine("Disposing B");
}
protected override void Dispose(bool bDisposing)
{
if (!m_bDisposed)
{
if (bDisposing)
{
// Dispose managed resources
Console.WriteLine("Dispose B");
}
// Dispose unmanaged resources
}
}
}
class classC : classB, IDisposable
{
private bool m_bDisposed;
public void Dispose()
{
Dispose(true);
base.Dispose();
GC.SuppressFinalize(this);
Console.WriteLine("Disposing C");
}
protected override void Dispose(bool bDisposing)
{
if (!m_bDisposed)
{
if (bDisposing)
{
// Dispose managed resources
Console.WriteLine("Dispose C");
}
// Dispose unmanaged resources
}
}
}
}
If you wanted to use [basetype].Invoke("Dispose"...) then you could implement the function call without the debugger complaining. Then later when the base type actually implements the IDisposable interface it will execute the proper call.
If you wanted to use [basetype].Invoke("Dispose"...) then you could implement the function call without the debugger complaining. Then later when the base type actually implements the IDisposable interface it will execute the proper call.
Try this. It's a one-line addition to the Dispose() method, and calls the ancestor's dispose, if it exists. (Note that Dispose(bool) is not a member of IDisposable)
// Disposal Helper Functions
public static class Disposing
{
// Executes IDisposable.Dispose() if it exists.
public static void DisposeSuperclass(object o)
{
Type baseType = o.GetType().BaseType;
bool superclassIsDisposable = typeof(IDisposable).IsAssignableFrom(baseType);
if (superclassIsDisposable)
{
System.Reflection.MethodInfo baseDispose = baseType.GetMethod("Dispose", new Type[] { });
baseDispose.Invoke(o, null);
}
}
}
class classA: IDisposable
{
public void Dispose()
{
Console.WriteLine("Disposing A");
}
}
class classB : classA, IDisposable
{
}
class classC : classB, IDisposable
{
public void Dispose()
{
Console.WriteLine("Disposing C");
Disposing.DisposeSuperclass(this);
}
}
public class MyVeryBaseClass {
protected void RealDispose(bool isDisposing) {
IDisposable tryme = this as IDisposable;
if (tryme != null) { // we implement IDisposable
this.Dispose();
base.RealDispose(isDisposing);
}
}
}
public class FirstChild : MyVeryBaseClasee {
//non-disposable
}
public class SecondChild : FirstChild, IDisposable {
~SecondChild() {
Dispose(false);
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
base.RealDispose(true);
}
protected virtual void Dispose(bool bDisposing) {
if (!m_bDisposed) {
if (bDisposing) {
}// Dispose managed resources
} // Dispose unmanaged resources
}
}
That way, you are responsible to implement right only the first class which is IDisposable.

Categories

Resources