Disposing object in C# - c#

I have written the following class:
public class CoupleFrames
{
public CoupleFrames(ColorImageFrame cif, Bitmap df)
{
this.colorFrame = cif;
this.desktopFrame = df;
}
public ColorImageFrame colorFrame;
public Bitmap desktopFrame;
}
Now I'm using the following code for disposing the variables.
CoupleFrames cf = new CoupleFrames(frame1, frame2);
// some code...
cf.colorFrame.Dispose();
cf.desktopFrame.Dispose();
I'm not sure that this is the correct way. Someone can suggest me the correct way for disposing the entire object?

I'm not sure that this is the correct way. Someone can suggest me the correct way for disposing the entire object?
Sure - you should make CoupleFrames implement IDisposable, and its Dispose method should dispose of the objects it "owns". For example:
public sealed class CoupleFrames : IDisposable
{
private readonly ColorImageFrame colorFrame;
private readonly Bitmap desktopFrame;
public CoupleFrames(ColorImageFrame cif, Bitmap df)
{
// TODO: Argument validation, unless it's valid for these parameters
// to be null, in which case the Dispose method would need to be careful.
this.colorFrame = cif;
this.desktopFrame = df;
}
public void Dispose()
{
colorFrame.Dispose();
desktopFrame.Dispose();
}
}
A few points to note:
You should make sure it's clear that the CoupleFrame really "owns" these constituent objects. Disposal relies on a clear ownership model
If CoupleFrame isn't sealed (and can't be) you may need to go into a more complicated pattern with virtual methods and finalizers. It can get very complicated, and you should read the advice given here by Joe Duffy et al. If your class is sealed, a lot of that complexity goes away
Public fields are generally a bad idea (in terms of encapsulation), which is why I've made them private here. I've also made them readonly, as if they can be changed later you need to think about whether changing them should dispose of the previously-referenced object etc.
By making CoupleFrame implement IDisposable, you're basically telling all clients that they should dispose of any instance they own. If you're not happy with imposing that burden, you need to rethink the design a bit.

I would implement the Dispose pattern
public class CoupleFrames : IDisposable
{
public CoupleFrames(ColorImageFrame cif, Bitmap df)
{
this.colorFrame = cif;
this.desktopFrame = df;
}
public ColorImageFrame colorFrame;
public Bitmap desktopFrame;
private bool disposed;
public void Dispose()
{
Dispose(true);
GC.SupressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposed)
{
return;
}
if (disposing)
{
colorFrame.Dispose();
desktopFrame.Dispose();
}
disposed = true;
}
}

You can use the IDisposable interface.
public class CoupleFrames : IDisposable
{
....
public void Dispose()
{
// Your disposing code here
}
~CoupleFrames()
{
Dispose();
}
}
You can use the destructor to call the Dispose method since the object can sometimes be deleted by the GC.

Make CoupleFrames Implement the Idisposable Interface.
public class CoupleFrames : IDisposable
{
public CoupleFrames(ColorImageFrame cif, Bitmap df)
{
this.colorFrame = cif;
this.desktopFrame = df;
}
public ColorImageFrame colorFrame;
public Bitmap desktopFrame;
public void Dispose()
{
cf.colorFrame.Dispose();
cf.desktopFrame.Dispose();
}

Related

Override Lists Remove function failed

I am currently trying to override the Remove function of the generic List-Class. But I am struggling with one tiny part of my approach - with the reference to an object outside of the Remove-method.
public new void Remove(ref string item)
{
if (Count > 9)
{
Remove(this[0]);
}
base.Remove(item);
}
This method doesnt work because it is not overriding the actual Remove-method.
Does anyone know how to handle this?
EDIT: in the remove function I want to call a method on the reference object.
EDIT2: my current version
class SocketList<WebSocketConnection>
{
private List<WebSocketConnection> theList = new List<WebSocketConnection>();
public void Remove(ref WebSocketConnection obj)
{
obj.Dispose();
theList.Remove(obj);
// additional stuff
}
}
But in this version it is not possible to call the Dispose method on the referenced object. Im getting a message that says that there is no such method available for this object.
EDIT3: This is the Class in which I want to call the Dispose method
public class WebSocketConnection : IWebSocketConnection
{
{...}
// Flag: Has Dispose already been called?
private bool disposed = false;
// Instantiate a SafeHandle instance.
private SafeHandle handle = new SafeFileHandle(IntPtr.Zero, true);
{...}
// 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 (disposed)
return;
if (disposing)
{
handle.Dispose();
// Free any other managed objects here.
//
}
// Free any unmanaged objects here.
//
disposed = true;
}
}
You can´t override any member of List<T> because non of them is virtual. Also new won´t solve this because it simply hides the base-implementation. You may your list as MyExtList<MyClass> a = new MyExtList<MyClass>(). However whenever you cast this instance to its base-class also the base-implementation is used instead of your "overridden" one.
However you can do the following to achieve what you really want:
class MyExtList<T>
{
private List<T> theList = new List<T>();
public void Remove(T obj)
{
theList.Remove(obj)
// additional stuff
}
}
Thuse you won´t even need inheritance of List<T> but use a compoisition which gives you much more flexibility on what you offer to the user of your class. With your current implementation the user could do everything with the list what he could do with the generic List-implementation also. However in most situation you´re just interested in providing a few methods instead of all. So you can nicely hide everything you won´t provide to the outside by making a completely new class that uses List<T> instead of deriving from it.

How to implement IDisposable interface in a class inherited from SocketAsyncEventArgs

I work on a huge project in C# .NET 4.0. There is a custom class inherited from System.Net.Sockets.SocketAsyncEventArgs class. Something like the following:
public class SocketTaskArgs : SocketAsyncEventArgs
{
public SocketTaskArgs()
{
Completed += someEventhHandler;
}
public void CleanUp()
{
Completed -= someEventhHandler;
}
/*
There is a lot of code here that is unimportant at the moment.
*/
}
So, I wanted to move the content of CleanUp() method to Dispose(bool) method.
As first, I checked the source code of the base class - SocketAsyncEventArgs (using Go To Definition so that I saw metadata as source). I found out, this class implements IDisposable interface. Nice, I just need to override the Dispose(bool) method, don't I? (See IDisposable Interface on MSDN, the "IDisposable and the inheritance hierarchy" section, for more details). Nothing new for me... Unfortunately, the SocketAsyncEventArgs class is implemented as following:
public class SocketAsyncEventArgs : EventArgs, IDisposable
{
public void Dispose();
//some other stuff here
}
That means, there is no way how to override Dispose(bool) method, as it's implemented as private instead of protected... What is the reason for this?
Next, I read about SocketAsyncEventArgs.Dispose() method on MSDN. The funny thing is that, it contains the following section:
Notes to Inheritors
Dispose can be called multiple times by other
objects. When overriding Dispose(Boolean), be careful not to reference
objects that have been previously disposed of in an earlier call to
Dispose. For more information about how to implement Dispose(Boolean),
see Implementing a Dispose Method.
Wait... what?
When overriding Dispose(Boolean), ...
How am I supposed to override Dispose(Boolean)?
What is the recommended way to implement IDisposable interface in this case?
There doesn't seem to be anything stopping you from implementing IDisposable on your child class, take this example:
public class DisposableParent : IDisposable
{
public void Dispose()
{
Console.WriteLine("The parent was disposed.");
}
}
public class DisposableChild : DisposableParent, IDisposable
{
public new void Dispose()
{
base.Dispose();
Console.WriteLine("The child was disposed.");
}
}
public class Program
{
public static void Main()
{
using (DisposableChild c = new DisposableChild()) { }
Console.ReadKey(true);
}
}
Gives the following output:
The parent was disposed.
The child was disposed.
The compiler warns about hiding the dispose of the parent class in the child, so using the new operator gets rid of that warning, just make sure to call the base class Dispose from the child class (and implement it the right way).
The dispose for the child would become something like:
public class DisposableChild : DisposableParent, IDisposable
{
private bool _disposed = false;
public new void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (!_disposed)
{
base.Dispose();
Console.WriteLine("The child was disposed.");
_disposed = true;
}
}
}
}
And yes, this still works if you do something like:
using (DisposableParent p = new DisposableChild())
{
}
But something like this can break it:
public class Program
{
public static void Main()
{
DisposableChild c = new DisposableChild();
DisposeOfIt(c);
Console.ReadKey(true);
}
public static void DisposeOfIt(DisposableParent p)
{
p.Dispose();
}
}
Only prints out that the parent was disposed. So if you used this method you would have to be careful about controlling the lifetime of your objects.

Understanding disposable objects

I've looked in SO about a question like this one, and even that I've found quite a few, any of those threw any light into this matter for me.
Let's assume I have this code:
public class SuperObject : IDisposable
{
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing) { }
}
Do I need the protected virtual void Dispose(bool) on SuperObject? Since there is really nothing to dispose there.
public interface ICustom : IDisposable { }
public class Custom : ICustom
{
public SuperObject Super { get; protected set; }
public Custom()
{
Super = new SuperObject();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public virtual void Dispose(bool disposing)
{
if (!disposing) return;
if (Super != null)
Super.Dispose();
}
}
public class Foo
{
public Foo()
{
using (var c = new Custom())
{
//do magic with c
}
}
}
Now what happens if I want/need/try to use Custom on a class like System.Web.Mvc.Controller which already implements and has implemented IDisposable?
public class Moo : Controller
{
Custom c;
public Moo()
{
c = new Custom();
}
// Use c throughout this class
}
How to properly dispose c in Moo?
The normal approach is to apply the standard IDisposable implementation - HOWEVER this is really only necessary if your class or some class that derives from it will use UNmanaged resources - this case is infact VERY rare (and when this case does apply it is better to wrap the unmanaged resource in its own class that has a full standard IDisposable implementation).
So assuming you are not dealing with UNmanaged resources (raw file handles, globally alloced memeory etc) and are only dealing with members that are disposable (i.e that have managed resources and implement IDisposable) then you can safely get a way with a mimimal implimentation of IDispose - that is:
Just have a single void Dispose() method. In that method just call dispose on dispoable members and then Dispose on the base class if its disposable. If you have a class hierachy its ok to make this Dispose virtual. There is no need to have a Dispose(bool) method. Nor is there any need to check if the object is disposed - because all your doing is calling dipsose on other objects and those implementation will do that check.
If you don't like the mimimal appraoch then apply the standard full implimentation (but it is not strictly necessary). I.e either do a standard implimentation because your a stickler for following the recommended approach OR do a simple minimal (but correct) implementation - but don't do something in between (i.e not standard, not simple or not correct)!
See this question for more details: Minimal IDispose implimenation for managed resources only
So in your case the following is the mimimal implimentation:
public class SuperObject : IDisposable {
public void Dispose() {
// Dispose code...just call dispose on dispoable members.
// If there are none then no need to implement IDisposable!
}
}
public interface ICustom : IDisposable { }
public class Custom : ICustom {
public SuperObject Super { get; protected set; }
public Custom() {
Super = new SuperObject();
}
public void Dispose() {
if (Super != null)
Super.Dispose();
}
}
public class Moo : Controller {
Custom c;
public Moo() {
c = new Custom();
}
public Dispose() {
if (c!=null)
c.Dispose()
base.Dispose();
}
}
Note that if Super object does not have any disposable resources then there is no point in implementing IDisposable and having a Dispose method. If Customs only disposable object is SuperObject then the same applies there, and again the same logic rocks through to Moo. Finally then if all the above applies and there are no other disposable objects around all you need really need is:
public class Moo : Controller {
Custom c;
public Moo() {
c = new Custom();
}
public Dispose() {
base.Dispose();
}
}
How to properly dispose c in Moo?
public class Moo : Controller
{
Custom c;
public Moo()
{
c = new Custom();
}
// Use c throughout this class
protected override Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
c.Dispose()
}
}
And that also answers your first question, Controller needs to make its Dispose(bool) method protected virtual or the above would not be possible.
But a few notes:
you don't have any isDisposed logic. It is a good idea to do the disposing only once, and you may want to trap usage-after-dispose.
omitting destructors (finalizers) is in itself a good idea but you now have the extra constraint that no derived class should own an unmanaged resource.

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

Export with MEF in Caliburn.Micro - Increasing memory problem

I have problem with increasing memory. I use MEF in caliburn.micro on creation new screen - WPF window.
View model of screen/view look like this:
[Export(typeof(IChatViewModel))]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class ChatViewModel : Screen, IChatViewModel
{}
On creation I use ExportFactory, controler is here:
public interface IViewModelsControler
{
ExportLifetimeContext<IChatViewModel> CreatChatViewModel();
}
[Export(typeof(IViewModelsControler))]
public class ViewModelsControler : IViewModelsControler
{
[Import]
public ExportFactory<IChatViewModel> ChatViewFactory { get; set; }
public ExportLifetimeContext<IChatViewModel> CreatChatViewModel()
{
return ChatViewFactory.CreateExport();
}
}
I use ViewModelsControler class in ChatScreenManager class. This class Open/Remove chat screen.
Here is it:
[Export(typeof(IChatScreenManager))]
public class ChatScreenManager : IChatScreenManager
{
private IWindowManager _windowManager;
[Import]
public IViewModelsControler ViewModelControler { get; set; }
[ImportingConstructor]
public ChatScreenManager(IWindowManager windowManager)
{
_windowManager = windowManager;
ActiveChatScreens = new Dictionary<string, ExportLifetimeContext<IChatViewModel>>();
}
//store active screen
public Dictionary<string, ExportLifetimeContext<IChatViewModel>> ActiveChatScreens { get; set; }
public void OpenChatScreen(DetailData oponent, string avatarNick, BitmapImage avatarImage)
{
if (!ActiveChatScreens.ContainsKey(oponent.Info.Nick))
{
//create new chat screen with view model controler
ExportLifetimeContext<IChatViewModel> chatScreen = ViewModelControler.CreatChatViewModel();
//show
_windowManager.Show(chatScreen.Value);
//add ref to the dic
ActiveChatScreens.Add(oponent.Info.Nick, chatScreen);
}
}
public void RemoveChatScreen(string clossingScreen)
{
MessageBox.Show(GC.GetTotalMemory(true).ToString());
ActiveChatScreens[clossingScreen].Dispose();
ActiveChatScreens.Remove(clossingScreen);
GC.Collect();
GC.SuppressFinalize(this);
MessageBox.Show(GC.GetTotalMemory(true).ToString());
}
}
And my problem is:
I call OpneChatScreen method from ChatScreenManager it open new WPF window
Add reference on this window to the dictionary.
When I am closing window I call RemoveChatScreen.
In RemoveChaScreen:
I get total memory, for example is it 37,000K
Then I call Dipose method on ExportLifetimeContext chatScreen
Force GC
And get total memory, for example is it 39,000K
Memory usage is stil increasing. I hope if I call Dispose method on object ChatViewModel and also ChatView object these object are destroyed.
Do not force GC! Also, the Dispose() method should follow removal from your collection.
public void RemoveChatScreen(string closingScreen)
{
MessageBox.Show(GC.GetTotalMemory(true).ToString());
IChatViewModel chatWindow = ActiveChatScreens[closingScreen]
// remove from collection - GC may pass over object referenced in collection
// until next pass, or 3rd pass...who knows, it's indeterminate
ActiveChatScreens.Remove(closingScreen);
// all clean up should be performed within Dispose method
chatWindow.Dispose();
//GC.Collect();
//GC.SuppressFinalize(this);
MessageBox.Show(GC.GetTotalMemory(true).ToString());
}
Forcing garbage collection is not recommended. There are ways to work with GC, however, and that is typically done in the Dispose() method of the disposable class. Your derived ChatView object should be defined something like:
class ChatView : IChatViewModel, IDisposable
{ }
ChatView requires a Dispose() method be implemented. There is a pattern to follow (from MSDN) when creating disposable classes:
// Design pattern for a base class.
public class ChatView : IChatViewModel, IDisposable
{
private bool disposed = false;
//Implement IDisposable.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
// Free other state (managed objects).
}
// Free your own state (unmanaged objects).
// Set large fields to null.
disposed = true;
}
}
// Use C# destructor syntax for finalization code.
~ChatView()
{
// Simply call Dispose(false).
Dispose (false);
}
}

Categories

Resources