Friday, June 18, 2004

Leaks, leaks, everywhere...

I think I'm becoming an authority on finding .NET leaks: I just found a handle leak on the EventLog class.
The problem, this time is with the static method (decompiled with Lutz Roeder's .NET Reflector):

public static void WriteEntry(string source, string message, EventLogEntryType type, int eventID,
short category, byte[] rawData)
{
EventLog log1 = new EventLog();
log1.Source = source;
log1.WriteEntry(message, type, eventID, category, rawData);
}



Noticed? EventLog implements IDisposable and the code should be this:

public static void WriteEntry(string source, string message, EventLogEntryType type, int eventID,
short category, byte[] rawData)
{
using (EventLog log1 = new EventLog())
{
log1.Source = source;
log1.WriteEntry(message, type, eventID, category, rawData);
}
}



So, the lesson is: if you care about not leaking handles (e.g., in server applications, where a few handles per processing unit can shut down a whole service), don't use LogEvent static methods. Create an instance and call its methods, and dispose it yourself.

Comments:
No leaks.... just not determined finalization. The GC will pickup the unmanaged resource has not been referenced and clean up on the next sweep.

regards

leppie
 
Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?