When operating on a large number of files using the SOLIDWORKS Document Manager API, I discovered a memory leak. The memory leak occurs at: Save(). How should this be addressed? Thanks!
Environment: SW2018SP5, SW2023SP5.
Example:
static void Main(string[] args)
{
static string sLicenseKey ="";
string fileName = "Part.SLDPRT";
Process currentProcess = Process.GetCurrentProcess();
for (int i = 0; i < 1000; i++)
{
if (File.Exists(fileName))
{
SwDMDocument19 swDoc = null;
SwDMClassFactory swClassFact = null;
SwDMApplication4 swDocMgr = null;
SwDmDocumentOpenError returnValue = 0;
// Refresh process information to get the latest data
currentProcess.Refresh();
// Get memory usage (in bytes)
long workingSetMemory = currentProcess.WorkingSet64; // Physical memory usage
long privateMemory = currentProcess.PrivateMemorySize64; // Private memory usage
// Convert to MB with two decimal places
double workingSetMemoryMB = workingSetMemory / (1024.0 * 1024.0);
double privateMemoryMB = privateMemory / (1024.0 * 1024.0);
try
{
swClassFact = new SwDMClassFactory();
swDocMgr = (SwDMApplication4)swClassFact.GetApplication(sLicenseKey);
swDoc = (SwDMDocument19)swDocMgr.GetDocument(
fileName,
SwDmDocumentType.swDmDocumentPart,
false,
out returnValue
);
if (swDoc.Save() != SwDmDocumentSaveError.swDmDocumentSaveErrorNone) // Potential memory leak!
{
Console.WriteLine("Failed to save!");
}
else
{
if (i % 100 == 0) Console.WriteLine();
Console.Write(\\\$"\\r{DateTime.Now} Saved successfully({i}). Memory Summary [WorkingSet: {workingSetMemoryMB:F2} MB, PrivateMemory: {privateMemoryMB:F2} MB]");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
if (swDoc != null)
{
swDoc.CloseDoc();
}
swDoc = null;
swDocMgr = null;
swClassFact = null;
}
}
else
{
Console.WriteLine(\\\$"File Not Found: {fileName}");
}
}
Console.WriteLine("\\nDone.");
Console.ReadLine();
}
