My code (successfully) reads from several worksheets, makes several lists, and puts them all in a dictionary for other threads to use. The createLists()
function loops every minute to check for any new data in the excel workbook and updates the lists.
If I run my code without this function, I see no memory leak. But if I include this function, I can easily see memory getting eaten up every time it loops (every minute).
Here's my function:
public static void createLists()
{
list_dictionary.Add(1, example_list1);
list_dictionary.Add(2, example_list2);
list_dictionary.Add(3, example_list3);
list_dictionary.Add(4, example_list4);
list_dictionary.Add(5, example_list5);
list_dictionary.Add(6, example_list6);
while (true)
{
try
{
Console.WriteLine("In create");
excel = new Excel.Application();
excel_workbook = excel.Workbooks.Open(@"C:\Local Code\Excel\Book1.xlsx");
for (int s = 1; s <= 6; s++)
{
Excel._Worksheet excel_worksheet = excel_workbook.Sheets[s];
Excel.Range excel_range = excel_worksheet.UsedRange;
list_dictionary[s].Clear();
int row_count = excel_range.Rows.Count;
int col_count = excel_range.Columns.Count;
for (int x = 1; x <= row_count; x++)
{
for (int y = 1; y <= col_count; y++)
{
if (excel_range.Cells[x, y] != null && excel_range.Cells[x, y].Value2 != null)
{
list_dictionary[s].Add(excel_range.Cells[x, y].Value2.ToString());
}
}
}
GC.Collect();
GC.WaitForPendingFinalizers();
Marshal.ReleaseComObject(excel_range);
Marshal.ReleaseComObject(excel_worksheet);
}
}
catch (Exception e)
{
Console.WriteLine("MANTIS");
Console.WriteLine(e);
Console.WriteLine(e.StackTrace);
}
finally
{
Console.WriteLine("CLEAN UP");
GC.Collect();
GC.WaitForPendingFinalizers();
Marshal.ReleaseComObject(excel_workbook);
Marshal.ReleaseComObject(excel);
}
Console.WriteLine("Out create");
Thread.Sleep(10000);
}
}
}
There are 6 "sheets" in the workbook, for I have a for loop to iterate over them and update the corresponding list in the list_dictionary
. I ReleaseComObject
the Excel.Range
and Excel._Worksheet
every loop, then the entire Excel.Workbooks
and Excel.Application
at the end of the while loop.
Any idea where I'm failing to release memory?