Why IDisposable interface? [duplicate] - c#

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
}

Related

Dispose/finalize pattern : disposing managed ressources

Let's imagine I have a class named Base with 3 attributes :
class Base : IDisposable
{
private string _String;
private Class1 classe1;
private int foo;
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
public virtual void Dispose(bool disposing)
{
if (disposing)
{
Console.WriteLine("Free Managed ressources");
//HOW TO FREE _String, class1 and foo ?!
}
Console.WriteLine("Free unmanaged ressources");
}
~Base()
{
this.Dispose(false);
}
}
and a classe named Class1 with 2 attributes :
class Class1
{
public int entier { get; set; }
public string Nom { get; set; }
}
My question is : How can I free the attributes of Base in the Dispose method ? (_String, classe1, foo)
My question is : How can I free the attributes of Base in the Dispose
method ? (_String, classe1, foo)
You don't need to, that's the job of the garbage collector. Implementing IDisposable is a way for the framework to let you release any unmanaged resources you have allocated, and dispose managed objects implementing IDisposable themselves (which in turn hold other unmanaged resources).
None of the managed objects at your disposable implement IDisposable, and they will be collected once there is no longer any objects pointing to your Base class. When will that happen? In an arbitrary time, when the GC see's that there is no longer space in generation 0, and it needs to collect. There is nothing you need to do.
Implementing IDisposable does not mean "this object will be collected immediatly once i run Dispose()", it merely means that the framework gives you a chance to reclaim any resources it might not be aware of (such as unmanaged ones). It is a recommended approach, if one implements a finalizer, to suppress the call to it via GC.SuppressFinalize, saving the GC the trouble of moving your object from the Finalizer Queue to the F-Reachable Queue, hence making it available for collection earlier.
when will these 3 attributes free from the heap ? The garbage
collector won't free them because I have GC.SuppressFinalize(this)
You have a basic misunderstanding of how the GC works and what SuppressFinalize means. The GC will run at an non-deterministic time, and you basically shouldn't care when that happens. It's his responsibility to clean up after you. Calling SuppressFinalize on an object implementing a finalizer does nothing more than set a bit in the objects header which the runtime checks when calling finalizers, which will suppress your finalizer from running
In this case, you shouldn't implement IDisposable at all, or if it was there because it was deemed very likely that it could be necessary in the future, then it would have an empty implementation. You certainly shouldn't have a finaliser in there; never have one unless you actually need one with 100% certainty.
There are a few cases where you would want to implement IDisposable, and in some of those cases you'd also want to have a destructor (which is the C# way of having a finaliser).
One is where you have something that it is really important to do when the object is finished with, most often undoing something you have previously done, such as releasing a handle that you'd obtained, closing a connection you'd opened, etc. but not managed memory. (All objects use managed memory, and all objects have their managed memory cleaned up for them if they're can't be used again and more managed memory is needed by something else, that's what the managed in "managed memory" means).
public class SomeClass : IDisposable
{
private IntPtr _someHandle;
public SomeClass(string someIdentifier)
{
_someHandle = GetHandle(someIdentifier);
}
public void Dispose()
{
ReleaseHandle(_someHandle);
}
}
So now whenever something that's been using a SomeClass is done with it, it calls Dispose() on it (perhaps implicitly via a using block) and all is cleaned up nicely.
But what if that doesn't happen? Well, that's why we might have a finaliser:
public class SomeClass : IDisposable
{
private IntPtr _someHandle;
public SomeClass(string someIdentifier)
{
_someHandle = GetHandle(someIdentifier);
}
public void Dispose()
{
ReleaseHandle(_someHandle);
_someHandle = null; // so we know not to release twice.
}
~SomeClass()
{
if(_someHandle != null)
ReleaseHandle(_someHandle);
}
}
So, here if the Dispose() doesn't get called, we still get the clean-up, because the normal garbage-collection process:
Realise you need more memory.
Find objects that aren't going to be used any more.
Reclaim the memory of those objects.
Has the following steps added:
Realise the object whose memory you were going to reclaim has a finaliser to run.
Put the object into a queue of other such objects.
(On a separate thread) run the finaliser of the object.
The object is no longer an object that "has a finaliser to run" as per step 4 above, so next time around it can be reclaimed.
All of this has downsides:
We can't guarantee when, if ever, this will happen.
We didn't get to reclaim as much memory in step 3, because there was such an object.
Garbage collection is generational, and playing nicely with generational collection for an object means either dying quickly or living a long time, dying just after the first time the GC tried to collect an object is pretty much the least optimal time.
We can get around the first two by calling Dispose() rather than letting finalisation happen, which is up to the user of the class, not the class itself. We get around the third by having an object that knows it doesn't need to be finalised mark itself as no longer needing to be:
public class SomeClass : IDisposable
{
private IntPtr _someHandle;
public SomeClass(string someIdentifier)
{
_someHandle = GetHandle(someIdentifier);
}
public void Dispose()
{
ReleaseHandle(_someHandle);
GC.SuppressFinalize(this);
}
~SomeClass()
{
ReleaseHandle(_someHandle);
}
}
If an object has been passed to GC.SuppressFinalize() then step 4 and subsequent don't happen.
The second case where you might what to implement IDisposable is where you have an IDisposable object as a field of another object that "owns" it (controls it's lifetime):
public class SomeOtherClass : IDisposable
{
private SomeClass _someObj;
public SomeOtherClass(string someIdentifier)
{
_someObj = new SomeClass(someIdentifier);
}
public void Dispose()
{
//If base type is disposable
//call `base.Dispose()` here too.
_someObj.Dispose();
}
}
Cleaning up a SomeOtherClass hence means cleaning up the SomeClass it has as a field. Note that here we do not have a finaliser here. We can't need a finaliser, because it would have nothing to do; at best it would do nothing and just have the downsides of finalisers mentioned above, at worse it would try to clean up _someObj without knowing whether this would happen before or after _someObj cleaning itself up and with _someObj queued to clean itself up in a way where it can assume nothing else will do the clean-up.
For the third case, consider if we combine the two cases with a class that has both an unmanaged resource it releases and a field which is a disposable class. Here if we are Dispose()d we want to clean up both, but if we are finalised we want to only clean up the unmanaged resource that is dealt with directly:
public sealed class SomeHybridClass : IDisposable
{
private IntPtr _someHandle;
private SomeClass _someObj;
public SomeHybridClass(string someIdentifier)
{
_someHandle = GetHandle(someIdentifier);
_someObj = new SomeClass(someIdentifier);
}
public void Dispose()
{
ReleaseHandle(_someHandle);
GC.SuppressFinalize(this);
_someObj.Dispose();
}
~SomeHybridClass()
{
ReleaseHandle(_someHandle);
}
}
Now, since there's repetition here, it makes sense to refactor them into the same method:
public sealed class SomeHybridClass : IDisposable
{
private IntPtr _someHandle;
private SomeClass _someObj;
public SomeHybridClass(string someIdentifier)
{
_someHandle = GetHandle(someIdentifier);
_someObj = new SomeClass(someIdentifier);
}
private void Dispose(bool disposing)
{
if(disposing)
{
_someObj.Dispose();
}
ReleaseHandle(_someHandle);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~SomeHybridClass()
{
Dispose(false);
}
}
And for a fourth case, imagine if this class wasn't sealed; it's derived types also need to be able to do this clean-up, so we make the parameterised Dispose(bool) method protected:
public class SomeHybridClass : IDisposable
{
private IntPtr _someHandle;
private SomeClass _someObj;
public SomeHybridClass(string someIdentifier)
{
_someHandle = GetHandle(someIdentifier);
_someObj = new SomeClass(someIdentifier);
}
protected virtual void Dispose(bool disposing)
{
// if this in turn was derived, we'd call
// base.Dispose(disposing) here too.
if(disposing)
{
_someObj.Dispose();
}
ReleaseHandle(_someHandle);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~SomeHybridClass()
{
Dispose(false);
}
}
However, these last two examples are really solving the wrong problems: They're solving the problem of how to have a class that has both a disposable type as a field and an unmanaged resource, and/or be part of a type hierarchy with this happening. Really you're much better off never getting into this situation; either have a class that only deals with an unmanaged resource (and is sealed) or has disposable types in fields, and you end up with only having the deal with the first two cases. If you deal with your unmanaged resources by deriving from SafeHandle then you are really only having to worry about the second case, and that also manages some difficult edge cases too.
Really, finalisers should very, very rarely be written, and when they are written they should be written to be as simple as possible, because there's enough complication inherent to them and the edge-cases around them as it is. You need to know how to deal with overriding protected virtual void Dispose(bool disposing) (note, should never be public) to deal with the legacy of when that had seemed like a good idea to someone, but not have inheritable classes with both unmanaged and managed-disposable resources forcing someone else into that position.
How can I free the attributes of Base in the Dispose method ? (_String, classe1, foo)
As should now be clear, those fields (attributes are a very different thing in .NET) don't need to be freed. The only resource they have is managed memory, so once they can't be reached (aren't in a static, aren't about to have something done to them in a method, and aren't in a field of something that is in either of those categories or a field of something that is in a field in either of those, etc.) their memory will be automatically reclaimed when needed.

Reason for Using IDisposable Interface

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.

Should Dispose methods be unit tested?

I am using C#. Is it advised to unit test dispose methods? If so why, and how should one test these methods?
Yes, but it might be hard. There are two things that can generally happen in Dispose implementation:
Unmanaged resources are released.
In this case it's pretty hard to verify that the code called, for example, Marshal.Release. A possible solution is to inject an object that can do the disposing and pass a mock to it during testing. Something to this effect:
interface ComObjectReleaser {
public virtual Release (IntPtr obj) {
Marshal.Release(obj);
}
}
class ClassWithComObject : IDisposable {
public ClassWithComObject (ComObjectReleaser releaser) {
m_releaser = releaser;
}
// Create an int object
ComObjectReleaser m_releaser;
int obj = 1;
IntPtr m_pointer = Marshal.GetIUnknownForObject(obj);
public void Dispose() {
m_releaser.Release(m_pointer);
}
}
//Using MOQ - the best mocking framework :)))
class ClassWithComObjectTest {
public DisposeShouldReleaseComObject() {
var releaserMock = new Mock<ComObjectReleaser>();
var target = new ClassWithComObject(releaserMock);
target.Dispose();
releaserMock.Verify(r=>r.Dispose());
}
}
Other classes' Dispose method is called
The solution to this might not be as simple as above. In most cases, implementation of Dispose is not virtual, so mocking it is hard.
One way is to wrap up those other objects in a mockable wrapper, similar to what System.Web.Abstractions namespace does for HttpContext class - i.e. defines HttpContextBase class with all virtual methods that simply delegates method calls to the real HttpContext class.
For more ideas on how to do something like that have a look at System.IO.Abstractions project.
Certainly can't hurt. Client code may try to use an object of your class after it has disposed of it. If your class is composed of other IDisposable objects, you should always be throwing the ObjectDisposedException exception if it is in a state which it is no longer usable.
Of course, you should only be testing the external state of your object. In the example below, I've made the property Disposed external to give me the state.
Consider:
internal class CanBeDisposed : IDisposable
{
private bool disposed;
public bool Disposed
{
get
{
if (!this.disposed)
return this.disposed;
throw new ObjectDisposedException("CanBeDisposed");
}
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
//// Dispose of managed resources.
}
//// Dispose of unmanaged resources.
this.disposed = true;
}
}
}
So how I would test this is thus:
CanBeDisposed cbd;
using (cbd = new CanBeDisposed())
{
Debug.Assert(!cbd.Disposed); // Best not be disposed yet.
}
try
{
Debug.Assert(cbd.Disposed); // Expecting an exception.
}
catch (Exception ex)
{
Debug.Assert(ex is ObjectDisposedException); // Better be the right one.
}
If your class creates and works with unmanaged resources, then you should definitely ensure that Dispose works as you expect it to - although it could be argued it is more of an integration test due to the type of hoops you're going to have to jump through.
If your class only creates / uses managed resources ( i.e. they implement IDisposable ) then all you really need to ensure is that the Dispose method on these resources is invoked at the correct time - if you are using some form of DI then you can inject a mock and assert that Dispose was called.
Look at the complexity of your dispose methods - if they are only a couple of lines long with maybe 1 condition, ask yourself if there really is a benefit in unit testing them.
Big yes - if your situation requires you to implement a Dispose function - you better make sure it does what you think!
For example, we have classes that coordinate database tasks (think SSIS packages, but with SqlConnection and SqlCommand and SqlBulkCopy etc.).
If I don't properly implement my Dispose, I could have an uncommitted SqlTransaction, or dangling SqlConnection. This would be VERY bad if I were running multiple instances of these database tasks in series.
As a practical tip (because yes, you should test Dispose()) my experience has been that there are two ways to do so without too much hassle.
IDisposer
The first follows Igor's accepted answer - inject something like an IDisposer, so that you can call
public void Dispose()
{
_disposer.Release(_disposable);
}
where
public interface IDisposer
{
void Release(IDisposable disposable);
}
Then all you need to do is mock the IDisposer and assert that it's called once and you're golden.
Factory
The second, and my personal favourite, is to have a factory that creates the thing you need to test disposal of. This only works when the factory produces a mockable type (interface, abstract class), but hey, that's almost always the case, especially for something that's to be disposed. For testing purposes, mock the factory but have it produce a mock implementation of the thing you want to test disposal of. Then you can assert calls to Dispose directly on your mock. Something along the lines of
public interface IFooFactory
{
IFoo Create(); // where IFoo : IDisposable
}
public class MockFoo : IFoo
{
// ugly, use something like Moq instead of this class
public int DisposalCount { get; privat set; }
public void Dispose()
{
DisposalCount++;
}
}
public class MockFooFactory
{
public MockFoo LatestFoo { get; private set; }
public IFoo Create()
{
LatestFoo = new MockFoo();
return LatestFoo;
}
}
Now you can always ask the factory (which will be available in your test) to give you the latest MockFoo, then you dispose of the outer thing and check that DisposalCount == 1 (although you should use a test framwork instead, e.g. Moq).

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