Has anyone else run into SOLIDWORKS crashing with memory access violations after long API runs where documents are opened and shown repeatedly?
One thing I discovered is that the issue is not always RAM usage. In many cases, it is GDI object exhaustion combined with unreleased COM objects.
For example, if you repeatedly do things like:
-
Open documents
-
Make documents visible
-
Activate windows
-
Create bitmaps / preview images
-
Switch between drawings, parts, and assemblies
-
Leave COM references alive for ModelDoc2, Feature, Component2, View, Face2, etc.
SOLIDWORKS can slowly accumulate GDI objects until it eventually crashes with an access violation.
I noticed this especially when doing large batch operations with hundreds or thousands of files where documents are opened visibly instead of silently.
A few things that helped:
-
Always close documents immediately after processing
-
Release COM objects aggressively with Marshal.ReleaseComObject
-
Set COM references to null afterward
-
Dispose Bitmap, Graphics, Font, Pen, Brush, and Image objects
-
Avoid leaving drawings open during long loops
-
Periodically call:
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
- Monitor the GDI Objects column in Task Manager
Example:
try
{
var model = swApp.OpenDoc6(path, type, options, "", ref errors, ref warnings);
// Process model
}
finally
{
if (model != null)
{
swApp.CloseDoc(model.GetTitle());
Marshal.ReleaseComObject(model);
model = null;
}
}
In my case, making documents visible was causing GDI count to climb very quickly.
Curious if anyone else has seen this, or if there are additional tricks to reduce GDI leaks in long-running SOLIDWORKS API jobs.
