I have an external (.Net) dll that I have to use for an application. Unfortunately that dll has several known memory leaks. We are working on getting the authors of the dll to fix the memory leaks, but in the mean time I was wondering what is the best way to use the dll without having to deal with the memory leaks?
Share
Moving the .Net assembly into its own AppDomain so you can unload the module periodically may help if the leaks are due to hanging onto object references “too long”, but most “memory leak” situations I’ve run into in .Net managed code are actually failure to release unmanaged resource handles – releasing handles, closing files, closing network connections, etc.
If the resources are owned by a responsible .Net managed object that releases its unmanaged handles in IDispose.Close(), but some bonehead code isn’t calling IDispose.Close when it’s supposed to, forcing a GC cycle or unloading the assembly’s AppDomain may help reclaim those orphaned unmanaged resources by “hurrying up” the eventual GC disposal of the owning managed objects.
If the handles are owned by bonehead code that doesn’t release them properly at all, unloading the assembly’s AppDomain is unlikely to help reclaim the orphaned handles.
Most Windows resources associated with handles will be recovered when the process terminates. This is a bit extreme, but if GC and AppDomain cycling don’t help, you could write a wrapper around the offending .NET assembly classes and use .NET remoting to jettison the offending assembly from your process entirely. How much data interaction goes on between the offending assembly’s classes and the rest of your app will determine whether this is at all feasible. If the offending assembly is fairly self-contained with a smallish number of interfaces entry points, this could be doable. With the offending assembly in its own process, you could shut it down periodically to purge the accumulated cruft, without having to shut down your own process.
Definitely hold that last idea for the absolute last resort. Try to find out what kind of memory or resource is being leaked and how it’s being leaked and whether AppDomain cycling will reclaim the lost resources.