Do not call Dispose of parts in dispose MEF - c#

I ran into a problem when the application ends the container does not call the Dispose method of the parts.
Application based on MEF.
When I explicitly call Dispose the container, then matod Dispose is called on the parts, but if you just close the program, the Dispose of the parts will not be called, why?
How to make sure that when you close the program were caused by the Dispose method of all parts of the container MEF?
[Export(typeof(IMyClass))]
[PartCreationPolicy(CreationPolicy.Shared)]
public class MyClass: IDisposable, IMyClass
{
private bool disposed = false;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if(!this.disposed)
{
if(disposing)
{
// Dispose managed resources.
}
disposed = true;
}
}
~MyClass()
{
Dispose(false);
}
}

When I explicitly call Dispose the container, then matod Dispose is called on the parts, but if you just close the program, the Dispose of the parts will not be called, why?
Because disposing the container when you are done with it is mandatory. If your program does not call CompositionContainer.Dispose() before exiting, then that is a bug in your program.

Wim Coenen, thanks, I thought that the destruction of MEF must call Destruct on parts.
I made ​​sure to work the way I need to:
public partial class MyBootstrapper : MefBootstrapper
{
public MyBootstrapper()
{
App.Current.Exit += new ExitEventHandler(Current_Exit);
}
void Current_Exit(object sender, ExitEventArgs e)
{
if (this.Container != null)
this.Container.Dispose();
}
...

Related

Properly dispose derived class

I am trying to implement the IDisposable pattern on a derived class, and it's not working as expecting to work,
Suppose I have two classes and I want to call the Dispose method of the derived class:
Below is the code of my base class
public class BaseClass : IDisposable
{
// To detect redundant calls
private bool _disposedValue;
// Public implementation of Dispose pattern callable by consumers.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// Protected implementation of Dispose pattern.
protected virtual void Dispose(bool disposing)
{
if (!_disposedValue)
{
if (disposing)
{
// TODO: dispose managed state (managed objects)
}
// TODO: free unmanaged resources (unmanaged objects) and override finalizer
// TODO: set large fields to null
_disposedValue = true;
}
}
}
And I've something like this as a derived class
public class DerivedClass : BaseClass
{
// To detect redundant calls
private bool _disposedValue;
// Protected implementation of Dispose pattern.
protected override void Dispose(bool disposing)
{
if (!_disposedValue)
{
if (disposing)
{
}
_disposedValue = true;
}
// Call base class implementation.
base.Dispose(disposing);
}
}
And I've some wrapper class
public class WrapperClass : IDisposable
{
public ReadOnlyCollection<BaseClass> Items { get; set;}
// To detect redundant calls
private bool _disposedValue;
// Public implementation of Dispose pattern callable by consumers.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// Protected implementation of Dispose pattern.
protected virtual void Dispose(bool disposing)
{
if (!_disposedValue)
{
if (disposing)
{
foreach (var item in Items)
{
item.Dispose();
}
}
_disposedValue = true;
}
}
}
My issue is in the wrapper class, it doesn't call the Dispose method of the DerivedClass, and it calls the Dispose method of the BaseClass instead.
Update
It's my bad, I forget to say that the collections of items were created by NSubstitute like below:
// Having this will not call the Dispose method of the derived class
Items = new ReadOnlyCollection<BaseClass>(new List<BaseClass>
{
Substitute.For<DerivedClass>()
})
// Having this will call the Dispose method of the derived class
Items = new ReadOnlyCollection<BaseClass>(new List<BaseClass>
{
new DerivedClass>()
})
The public implementation of the Dispose() pattern in the documentation is there as an example to handle every case and contingency. It's always "safe" to do the whole thing, but it's also true that most of the time you can skip most of the pattern.
Especially regarding finalizers: you should only need a finalizer if you are creating an original wrapper implementation for a brand new kind of unmanaged resource. Each unmanaged resource type only needs one finalizer, at the root of the IDisposable inheritance tree. And if you don't add a finalizer, you don't need to worry about GC.SuppressFinalize(). Remove that, and some other balls drop as well.
In short, we can reduce the pattern for your DerivedClass all the way down to this:
public class DerivedClass : BaseClass
{
}
This DerivedClass type still provides the Dispose() method and IDisposable implementation inherited from it's parent, and if it doesn't introduce any other unmanaged resources that's all it needs.
My issue is in the wrapper class, it doesn't call the Dispose method of the DerivedClass, and it calls the Dispose method of the BaseClass instead.
When the base.Dispose() calls Dispose(true) the method override in the derived class is executed, which in turn will call base. Dispose(true).
DerivedClass doesn't appear to override Dispose(). Consequently, the base class version is invoked.
Add a public void Dispose() method that calls your protected void Dispose(bool disposing) implementation in DerivedClass.

Dispose invoked in run time when image is added through Import process

I have an application where I use a custom button. For this I use separate drawing class for the drawing. The drawing class was derived from IDisposable and I have invoked GC.SuppressFinalize(this) in its interface. Everything works fine, but when I import an image for button, the dispose is invoked which disposes my image which is leading to an Invalid exception.
We are using GC.SuppressFinalize(this) for disposing the managed resources used in our application and I found this is causing the issue.
This is a simple code for replication.
public class Custom : Control
{
private DrawingClass drawingClass;
public Custom()
{
this.drawingClass = new DrawingClass();
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
if(Image != null)
e.Graphics.DrawImage(Image, this.ClientRectangle.Location);
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
Image.Dispose();
}
}
public Image Image { get; set; }
}
public class DrawingClass : IDisposable
{
public void Dispose()
{
GC.SuppressFinalize(this);
}
}
When I drag and drop this Custom control and try to assign an image using Import process, the dispose was invoked which disposes the Image which leading exception when drawing.
The Dispose was invoked from " System.Windows.Forms.UnsafeNativeMethod ".
Can someone suggest what is wrong or using GC.SuppressFinalize() does really cause problems ?
From https://learn.microsoft.com/en-us/dotnet/api/system.gc.suppressfinalize:
GC.SuppressFinalize()
This method sets a bit in the object header of obj, which the runtime checks when calling finalizers. A finalizer, which is represented by the Object.Finalize method, is used to release unmanaged resources before an object is garbage-collected. If obj does not have a finalizer, the call to the SuppressFinalize method has no effect.
Also, check out this stackoverflow topic on implementing Disposable: Finalizer and IDisposable

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 better implement .NET IDisposable classes?

Forgive me in advance if this question is a little too open-ended, but I've seen similar language discussion posts here so I figured I'd take the plunge.
Anyway, I have read several MSDN help pages and various other blogs on the subject of properly implementing IDisposable classes. I feel like I understand things pretty well, but I have to wonder if there's a flaw in the suggested class structure:
public class DisposableBase : IDisposable
{
private bool mDisposed;
~DisposableBase()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!mDisposed)
{
if (disposing)
{
// Dispose managed resources
mManagedObject.Dispose();
}
// Dispose unmanaged resources
CloseHandle(mUnmanagedHandle);
mUnmanagedHandle = IntPtr.Zero;
mDisposed = true;
}
}
}
Anytime the above is supposed to serve as a base class, you rely on the implementer of the subclass to properly override the Dispose(bool) method where necessary. In short, derived classes must ensure they invoke the base Dispose(bool) method from within their overridden version. If not, the base class' unmanaged resources may never get freed, defeating the primary purpose of the IDisposable interface.
We all know the benefits of virtual methods, but it seems like in this case their design falls short. In fact, I think this particular shortcoming of virtual methods manifests itself frequently when trying to design visual components and similar base/derived class structures.
Consider the following change, using a protected event rather than a protected virtual method:
public class DisposeEventArgs : EventArgs
{
public bool Disposing { get; protected set; }
public DisposeEventArgs(bool disposing)
{
Disposing = disposing;
}
}
public class DisposableBase : IDisposable
{
private bool mDisposed;
protected event EventHandler<DisposeEventArgs> Disposing;
~DisposableBase()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// This method is now private rather than protected virtual
private void Dispose(bool disposing)
{
if (!mDisposed)
{
// Allow subclasses to react to disposing event
AtDisposing(new DisposeEventArgs(disposing));
if (disposing)
{
// Dispose managed resources
mManagedObject.Dispose();
}
// Dispose unmanaged resources
CloseHandle(mUnmanagedHandle);
mUnmanagedHandle = IntPtr.Zero;
mDisposed = true;
}
}
private void AtDisposing(DisposeEventArgs args)
{
try
{
EventHandler<DisposeEventArgs> handler = Disposing;
if (handler != null) handler(this, args);
}
catch
{
}
}
}
With this design, the base class' Dispose(bool) method will always be called, regardless of whether subclasses subscribe to the Disposing event or not. The biggest flaw that I can see with this revised setup is that there is no predetermined order for when event listeners are called. This could be problematic if there are multiple levels of inheritance, e.g. SubclassA's listener might be triggered before its child SubclassB's listener. Is this flaw serious enough to invalidate my revised design?
This design dilemma makes me wish there were some sort of modifier for methods that was similar to virtual but which would ensure that the base class' method was always called, even if a subclass overrode that function. If there's a better way to achieve this, I would greatly appreciate your suggestions.
You're using an event here when really you want to use an inheritance mechanism like virtual. For scenarios like this where I want to ensure my implementation is always called but want to allow for base class customization I use the following pattern
private void Dispose(bool disposing)
if (mDisposed) {
return;
}
if (disposing) {
mManagedObject.Dispose();
}
// Dispose unmanaged resources
CloseHandle(mUnmanagedHandle);
mUnmanagedHandle = IntPtr.Zero;
mDisposed = true;
DisposeCore(disposing);
}
protected virtual void DisposeCore(bool disposing) {
// Do nothing by default
}
With this pattern I've ensured my base class Dispose implementation will always be called. Derived classes can't stop me by simply forgetting to call a base method. They can still opt into the dispose pattern by overriding DisposeCore but they can't break the base class contract.
The derived class can simply re-implement IDisposable and thus prevent your dispose method from being called, so you can't ensure that either.
Personally I wouldn't use either pattern. I prefer building on SafeHandle and similar mechanisms, instead of implementing finalizers myself.
Consider making it apparent that Dispose is not being called so someone will catch it. Of course Debug.WriteLine will only be called when the code is compiled with DEBUG compiler directive defined.
public class DisposableBase : IDisposable
{
private bool mDisposed;
~DisposableBase()
{
if (!mDisposed)
System.Diagnostics.Debug.WriteLine ("Object not disposed: " + this + "(" + GetHashCode() + ")";
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
You can break it down:
A destructor (finalizer) is only needed for unmanaged resources.
Using a Safehandle can turn an unmanged resource into a managed resource.
Ergo: You won't need a destructor. That halves the Dispose pattern.
The reference design uses a virtual void Dispose(bool) to cater for the Base/Derived class problem. This puts the burden on the derived class to call base.Dispose(disposing), the core of your question. I use 2 approaches:
1) Prevent it. With a sealed base-class you won't have to worry.
sealed class Foo:IDisposable
{
void Dispose() { _member.Dispose(); }
}
2) Check it. Like #j-agent's answer but conditional. When performance could be an issue then you don't want the finalizers in Production code:
class Foo:IDisposable
{
void Dispose() { Dispose(true); }
[Conditional("TEST")] // or "DEBUG"
~Foo { throw new InvalidOperation("somebody forgot to Dispose") }
}
The destructor is going to be called no matter if any subclass overrides Dispose() (can be via override or new) but your destructor is going to be called ( ~DisposableBase() ) so i bet putting your logic for cleanup there can be a good starting point.
Here is an intersting article about destructors: http://www.c-sharpcorner.com/UploadFile/chandrahundigam/UnderstandingDestructors11192005021208AM/UnderstandingDestructors.aspx

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.

Categories

Resources