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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With