.NET 2.0 Leaks to avoid ...

.NET2.0 leaks to avoid are:

1. Avoid calling Value.ToString() on an Ole IDataParamer.

This triggers a memory leak in Ole, where it is allocation strings but never releasing them. In one case, this caused the .NET2.0 runtime to become unstable,
and the whole process kicked out.
The event log had the event IDs 1000 & 1023, which was extremely misleading:

http://support.microsoft.com/kb/913384


BAD:

IDataParameter _param
...
string paramValue = _param.Value.ToString();

GOOD:

string paramValue = ((int)_param.Value).ToString();



2. Do not use finalizers ~() unless you need to
When implementing IDispose it is tempting to always implement the finalizer.
This means you have a pattern you can apply in most cases.
However, implementing a finalizer means the object hangs around longer, and
this can result in apparent leaks, obviously affecting performance.

3. Avoid Parsing and compiling a XSD Schema multiple times.
If possible, for performance reasons we should only parse a schema once!
However, there also appears to be memory leaks in the .NET2 schema parsing.

So I wrote the following code to compile the XSD once:

static XmlSchemaSet s_schemaSet;

...
XmlReader schemaReader = XmlReader.Create(_xsdUri);
XmlSchema schema = XmlSchema.Read(schemaReader, new ValidationEventHandler(OnValidation));
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.Add(schema);
schemaSet.Compile();
s_schemaSet = schemaSet;

...

4. Avoid recreating XmlSerializer objects, if possible.
Instead use a static instance:

if (mySerialiser == null)
mySerialiser = new XmlSerializer(this.GetType());



How to avoid leaks:

The only real way, is towards the end of a project, use a good profiler like ANTS or GlowCode.

Comments