InfernumDeus
InfernumDeus

Reputation: 1202

ClosedXML. Memory leak while Workbook.Save()

I need to add new worksheet from dataTable. For this task I use ClosedXML:

workbook.Worksheets.Add(dataTable);
workbook.Save();
workbook = new XLWorkbook(filePath); //reload file to avoid exception at next saving

My process used 128 Mb of memory but after Workbook.Save() this number is rised to 382 Mb. After I've added next worksheet memory usage rised from 464 Mb to 619 Mb. But actual file at this point was 1.6 Mb.

What could be the reason of this?

Upvotes: 2

Views: 10344

Answers (2)

Francois Botha
Francois Botha

Reputation: 4839

Upgrade to the latest version of ClosedXML which is v0.87 at this stage. Run the code in Release configuration and add the following code after you've disposed the XLWorkbook:

GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();

You should notice that memory drops back to an acceptable level.

Upvotes: 2

Evk
Evk

Reputation: 101483

XLWorkbook implements IDisposable which you should call to free any resources it holds. If you don't do this - they will only be released (assuming XLWorkbook implements proper finalizer) when instance is garbage collected, which will happen some time in the future. You should do it like this:

workbook.Save();
workbook.Dispose(); // < important
workbook = new XLWorkbook(filePath);

Of course better would be to wrap workbook into using statement or at least use try and finally to ensure release on exception, but that is not directly related to the question.

Upvotes: 6

Related Questions