IDisposable : Memory leaks - c#

I'm currently do a review of a C# app in which I see that :
public static bool ServiceExists(string servicename)
{
ServiceController[] services = ServiceController.GetServices();
foreach (ServiceController s in services)
{
if (s.ServiceName == servicename)
{
return true;
}
}
return false;
}
In this answer, Henk said that the non-use of Dispose() (or using) will not generate memory leaks, true or false?
Can I keep the previous code has it is or should I write someting like :
public static bool ServiceExists(string servicename)
{
ServiceController[] services = ServiceController.GetServices();
bool exists = false;
foreach (ServiceController s in services)
{
using(s)
{
if (s.ServiceName == servicename)
{
exists = true;
}
}
}
return exists;
}
What are the risks to no using Dispose() (or using) in this case?

A correctly written object shouldn't cause a memory leak if it's Dispose method isn't called. These days a .Net object which controls unmanaged resources should be doing so via a SafeHandle instance. These will ensure the native memory is freed even if Dispose is not called.
However it's very possible for objects which aren't written correctly to produce memory leaks if Dispose isn't called. I've seen many examples of such objects.
In general though if you are using an IDisposable instance which you own you should always call Dispose. Even if the object is correctly written it's to your benefit that unmanaged resources get cleaned up earlier instead of later.
EDIT
As James pointed out in the comments there is one case where not calling Dispose could cause a memory leak. Some objects use the Dispose callback to unhook from long lived events which if they stayed attached to would cause the object to reside in memory and constitute a leak. Yet another reason to always call Dispose

It all depends on what ServiceController.GetServices() is doing. If it is creating new instances of ServiceControllers when it is called, then it could cause a memory leak depending on what it needs to do (the ServiceController) in its Dispose method.
That said, adding 'using' in this case wouldn't fix it anyway as if you DID need to call dispose (implicitly via 'using' in this case) on each instance, it WOULDN'T as it returns whenever it finds a ServiceController with a matching name.
Therefore, if your first iteration found a matching ServiceController, all the other ServiceControllers wouldn't get disposed of anyway.

Related

C# dispose unmanaged resource outside "using" and "try/finalize" block

I want a method to return an unmanaged resource and later in the program dispose of that resource. Does the following implementation do what I intend ?
class DocxManager
{
// DocX is the unmanaged resource
public Docx createDocX(string pathToFile)
{
return new DocX(pathToFile);
}
public void makeChangesAndSaveDocX(DocX wordDoc)
{
wordDoc.Save();
// IS THIS WAY THE UNMANAGED RESOURCE FREED CORRECTLY AND NO MEMORY LEAK ?
((IDisposable)wordDoc).Dispose();
}
}
First off all, you seem to be misunderstanding the concept of managed and unmanaged resources. wordDoc is not an unmanaged resource, its a managed resource which happens to either directly hold an unmanaged resource or acts as a wrapper around some other IDisposable object (you don't care wich of the two is true). Its important you are clear on this because otherwise you will not implement correctly the IDisposable pattern when you need to. Read this for a very instructive answer on the subject and a few chuckles courtesy of Eric Lippert.
Does the following implementation do what I intend ?
No, it does not and to make things worse, the contract of DocXManager is simply horrible (more on that later).
What hapens if wordDoc.Save() throws and exception because the file is being used by another process, or maybe you've run out of space in the hard drive, or you've lost connection, etc.?
If the thrown exception is not recoverable (it's not handled anywhere in your code or it is but you will terminate it ASAP) then it's not really an issue and the runtime will clean up everything behind you when the process is terminated. On the other hand, if the exception is handled (warn the user the file is in use, the directory is not available, etc.) and the process keeps running then you've just maybe leaked a resource.
How to avoid this? Use a try-finally block:
public void makeChangesAndSaveDocX(DocX wordDoc)
{
try
{
wordDoc.Save();
}
finally
{
((IDisposable)wordDoc).Dispose();
}
}
Now you are sure that Dispose() will be called in any recoverable scenario.
So, is this good enough? Well....not exactly. The problem here is that makeChangesAndSaveDocX's (that should be MakeChangesAndSaveDocX by the way) contract is unclear. Who is responsible of disposing wordDoc? MakeChangesAndSaveDocX or the caller? Why one or the other? How does the consumer know that he doesn't need to worry about wordDoc once he's called MakeChangesAndSaveDocX? Or how is he supposed to know he can't use wordDoc after calling the public method MakeChangesAndSaveDocX? Why does DocXManager assume that the consumer will not need to use wordDoc after calling MakeChangesAndSaveDocX? Yuck...this is a mess.
I'd recommend you reconsider your approach and do one of the following:
If the method signature MakeChangesAndSaveDocX(DocX wordDoc) makes sense (somebody else can own wordDoc), then do not dispose wordDoc in MakeChangesAndSaveDocX. Let the caller carry that burden, he should be responsible because the object belongs to him not to MakeChangesAndSaveDocX.
If on the other hand, it makes no sense that somebody else who is not DocXManager owns wordDoc then wordDoc should be part of the state of DocXManager and you should reconsider the implementation of DocXManager to something allong the following lines:
public class DocXManager: IDisposable
{
private readonly DocX docX;
private bool disposed;
public DocXManager(string filePath)
{
docX = new DocX(filePath);
}
public void MakeChangesAndSaveDocX()
{
if (disposed)
throw new ObjectDisposedException();
docX.Save();
}
public void FrobDocX(Frobber frobber)
{
if (disposed)
throw new ObjectDisposedException();
frobber.Frob(docX);
}
public void Dispose()
{
if (disposed)
return;
Dispose(true);
disposed = true;
GC.SupressFinalize(this);
}
public void Dispose(bool disposing)
{
if (disposing)
{
//we can sefely dispose managed resources here
((IDisposable)docX).Dispose();
}
//unsafe to clean up managed resources here, only clean up unmanaged resources if any.
}
~DocXManager()
{
Dispose(false);
}
}
Now you've got a clear contract; DocManagerX is responsible of disposing correctly of DocX and the consumer is responsible of disposing correctly of any instance of DocManagerX he might use. Once responsibilities are clear, its easier to reason about code correctness and who should do what.
You'd use the manager in the following way:
using (var manager = new DocXManager(path))
{
manager.FrobDoxX(frobber);
manager.MakeChangesAndSaveDocX();
} //manager is guaranteed to be disposed at this point (ignoring scenarios where finally blocks are not executed; StackOverflowException, OutOfMemoryException, etc.)

How to properly use the dispose method on a class

I'm working on a database and I need to write the database to file when the database class is destroyed along with every else when the form is closed
This is how I'm currently calling it:
class database: IDisposable
{
List<databaseEntry> dDatabase;
public database()
{
dDatabase = new List<databaseEntry>;
}
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
StreamWriter sw = new StreamWriter(path);
string toWrite;
foreach (databaseEntry dE in dDatabase)
{
toWrite = dE.rfid.ToString() + " " + dE.currentArea.ToString() + " " + dE.itemName;
sw.WriteLine(toWrite);
}
sw.Close();
disposed = true;
}
}//destructor for database (saves database to file)
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
The Dispose method isn't called when I close the windows form that this class is open in.
This is for an assignment and I'm not allowed to use SQL for this.
You do not have control over when the Dispose method is called by the garbage collector. If you want to dispose resources when the form is closed, you should manually call the Dispose method when the form is closed.
This is achieved by listening to the FormClosed event of the form.
So you would do something similar to this:
Create this method:
private void Form1_FormClosed(Object sender, FormClosedEventArgs e)
{
if(this.database != null)
this.database.Dispose();
}
Put this line in your form's constructor:
this.FormClosed += Form1_FormClosed;
Since you're implementing IDisposable, another solution would be to wrap your database object instantiation in a using statement - this would automatically call Dispose once the code in the using statement completes.
Syntax for your use case is as follows:
using(database db = new database())
{
//use your db object
} //db is disposed here
Edit:
Matthew Watson’s comment made me realize my answer is over simplified and could be confusing (thanks for the comment Matthew). Here’s (most of) the real story:
All objects have a constructor and a destructor. If these are not specified the default constructor and destructor are used.
Constructor:
ClassName()
Destructor:
~ClassName()
The Constructor is called when you use the new keyword. The Destructor can be called once there is no longer a reference to that specific instance of an object. Notice I said can be called, not is called. Meaning at this point the object is eligible for garbage collection and could be freed when the garage collector runs. I will not go into detail here but just know that the garage collector does not always collect all the unreachable objects for performance reasons. This is one of the key reasons you would want to the IDisposable interface. You can immediately clean up resources when you know they are no longer being used vs. waiting for the GC to clean up the resources. When working with streams or database connections it is a good idea to implement the IDisposable interface.
With that said here is the updated answer (replacing the previous "default Dispose()" references with the destructor reference).
Since this is an assignment I am not going to give you the answer per se, but I'll get you close. The destructor (~database) is normally called by the garage collector when an instance of a database object is no longer reachable. By implementing the IDisposable interface you have provided an alternative to allowing the garage collector to dispose of the object. You are telling the garage collector "I know when and how these resources need to be freed" vs. free these resources when there are no longer references to the objects. But that only applies if you call your Dispose method; more specifically the line:
Dispose(true);
GC.SuppressFinalize(this);
This means "Garage collector, do not call the destructor (~database()) method, I have already handled it".
What you should do in this method is close any streams (StreamWriter) you have open.
Usage: The IDisposable interface has a nice construct in C# the using statement. This is in effect a try catch block where the Dispose method is called in the finally block. StreamWriter also implements IDisposable so you should think about implementing the using statement in your database class. Example:
using(StreamWriter writer = new StreamWriter()){
//do stuff with writer here
}
This is the pattern you should use for your database class in your form. I will let you figure out how to code that up.

Suppressing premature finalization of stream in .NET

I have the following logger-like class pattern:
public class DisposableClassWithStream : IDisposable
{
public DisposableClassWithStream()
{
stream = new FileStream("/tmp/file", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
writer = new StreamWriter(stream);
}
public void WriteLine(string s)
{
writer.WriteLine(s);
}
~DisposableClassWithStream()
{
Dispose();
}
private readonly object disposableLock = new object();
private bool isDisposed;
public void Dispose()
{
lock (disposableLock)
{
if (!isDisposed)
{
writer.Close();
stream.Close();
GC.SuppressFinalize(this);
isDisposed = true;
}
}
}
private FileStream stream;
private TextWriter writer;
}
and a very simple code using this class:
public static void Main(string[] args)
{
var t = new DisposableClassWithStream();
t.WriteLine("Test");
}
The code throws (nondeterministically), both on .net and mono, ObjectDisposedException caused by method Close of object writer as it tries to flush buffer to stream which is already disposed.
I understand that the reason is that GC finalizes stream before writer. How can I change the class pattern to be sure that stream is not disposed before the writer?
I tired to use GC.SuppressFinalize(writer) in the constructor, but I'm not sure if it is not too hacky.
Edit:
I would like to address the question of having finalizer in the first place. As mentioned at the beginning of the question, the class is used as a logger and I want to assure that all lines from writer are flushed to the hard disk before closing the process.
Do not create finalizer, unless your IDisposable implementation really works with unmanaged resources. FileStream and StreamWriter are managed resources.
Moreover, since SafeHandle was introduced, it is hard to imagine use-case, when any unmanaged resource couldn't be wrapped into managed SafeHandle. Do not follow blindly IDisposable implemetation from MSDN - it's OK, but it is intended for the case, when your type operates both managed and unmanaged resources.
Remove finalizer at all, and throw away GC.SuppressFinalize(this); from Dispose:
public void Dispose()
{
lock (disposableLock)
{
if (!isDisposed)
{
writer.Close();
stream.Close();
isDisposed = true;
}
}
}
Update.
Finalizers are intended for unmanaged resource cleanup.
You may consider finalizer as a place to close file handle, network socket, etc. This isn't a place for any application logic. In general, managed object during finalization resides in unusable state - there's no guarantee, that any of its IDisposables (like stream or writer in your sample) are not finalized already.
If you want to be sure, that particular log message is flushed into file, than write it and call writer.Flush(). Otherwise, if immediate flushing is undesirable for you, make sure, that you're calling dispose for the logger on application shutdown. Also note, that you can't protect from process termination, so don't be too paranoid with your logger.
Managed objects should not be cleaned up in the finalizer. The finalizer should only used for cleaning up unmanaged resources.
Rewrite your code as follows to dispose of managed resources when you are done with the streams.
public static void Main(string[] args)
{
using (var t = new DisposableClassWithStream())
{
t.WriteLine("Test");
}
}
And be sure to check out the Dispose Pattern article on MSDN
When a finalizer runs, most managed objects to which it holds references will meet one of the following criteria:
-1- Not care about cleanup, in which case the finalizer should do nothing with them.
-2- Be unable to perform cleanup in a thread-safe manner when invoked in the context of finalizer cleanup, in which case the finalizer should do nothing with them.
-3- Have already cleaned themselves up using their own finalizer, in which case the finalizer should do nothing with them.
-4- Have a Finalize method which hasn't run yet, but is scheduled to run at first opportunity, in which case the finalizer for the class holding the reference should do nothing with them.
Different objects will meet different criteria, and it may be difficult to know which of those criteria a particular object might meet, but for the vast majority of objects will meet any of the criteria, the required handling is the same: don't do anything with them in the finalizer.
There are a few rare scenarios involving things like weak events where finalizers may be able to do something useful with managed objects, but in nearly all such cases, the only classes which should have finalizers are those whose sole purpose is to managed the finalization cleanup of other intimately-related objects. If one doesn't understand all the wrinkles of finalization, including the differences between short and long weak references and how they interact with the finalizer, any finalizer one tries to write will likely do more harm than good.

Cleanly shutting down a DLL's Static events in a host I don't control

Does the following psuedo code accomplish my goal of cleaning up after myself when my DLL is being hosted by code I don't control?
More specifically, how do I clean up my objects created in my static constructor?
Do I need to suppress Finalize in the Disposable?
Am I guaranteed that the compiler or something will call IDisposable even if the Host doesn't?
Psuedo code:
public class MyDLL : SomeHostICantControl, IDisposable
{
public SpinLock MyDictionarySpinlock = new Spinlock; // approximate syntax
public static Dictionary<string, string> MyDictionary = null;
public static Timer MyCleanUpTimer = null;
public static MyDLL()
{
// Set up Cache Here ... how do I dispose of it?
MyDictionary = new Dictionary<string, string>();
// remove old data from the dictionary, use spinlock to sync writes
// or use concurrent dictionary in .NET 4
MyCleanUpTimer = new Timer(); // run every hour
}
// many instances will be created and disposed of. I have no control when or how often
public void MyDll()
{
this.MyHostEvent += New Event Handler....
}
//.. some event handler code here
public void Dispose()
{
this.MyHostEvent -= Event Handler.;
// Do I need to suppressFinalize here?
}
//~MyDll()
//{
// Is this the right place to clean up after my constuctor?
//}
}
Answering your questions in order:
Static fields exist for the lifetime of the application, as such they are "cleaned up" as a result of the application exiting (memory is reclaimed, files are closed etc.). You don't appear to be doing anything that might require explicit action to be taken to clean-up (e.g. flushing buffered data in a StreamWriter to file), but perhaps there are details missing in your code snippet.
You need to suppress finalize in your Dispose() method if your class has a finalizer (yours appears not to as it's commented out), or if someone can derive from your class and may introduce unmanaged resources that may need cleaning up. The latter applies here as your class is not marked sealed, so you should suppress finalize in Dispose().
The runtime will not call Dispose(), however it will call the finalizer if one is present. Note however that as you class instances don't appear to be using any unmanaged resources, a finalizer should not be required.

Guidelines For Dispose() and Ninject

So, I have a method exposed from a WCF service as such:
public GetAllCommentsResponse GetAllComments(GetAllCommentsRequest request)
{
var response = new GetAllCommentsResponse();
using(_unitOfWork)
try
{
Guard.ArgNotNull(request, "request");
var results = _unitOfWork.CommentRepository.Get(d => d.Id > 0).ToArray();
//... Do rest of stuff here
}
catch (Exception ex)
{
response.Success = false;
response.FailureInformation = ex.Message;
Logger.LogError("GetAllComments Method Failed", ex);
}
return response;
}
I have a global DataUnitOfWork object (which implements IDisposable) that gets instantiated by Ninject through a constructor argument when a service call comes in. When debugging, if I use
using(_unitOfWork)
the _unitOfWork object gets disposed immediately after going out of scope then gets called again by Ninject (although it's been marked as disposed, so nothing happens.) Without the using statement, Ninject handles the disposing.
Long story short, is there a general rule of thumb for this? I've been scared of the whole IDisposable thing after everything I read seems to indicate never to use it, or use it in certain eclectic situations, but it's always confused me.
Any input is appreciated.
Oh, also while I'm here typing anyway, why exactly is there a call to GC.SuppressFinalize() when disposing? How do Dispose and Finalize differ?
The CLR documentation states that whoever creates a Disposable object is responsible for calling Dispose. In this case the object is created by Ninject. That means you should not call Dispose explicitly.
Ninject disposes every Disposable object that has another scope other than InTransientScope as soon as the scope object to which the created object is tied is collected by GC. That's why every Disposable object should be Bindd with a scope that is not InTransientScope(). E.g. you can use InParentScope() from the NamedScope extension which will Dispose the object as soon as the object it is injected into is garbage collected.

Categories

Resources