TheGateKeeper
TheGateKeeper

Reputation: 4530

Terminating excel process

Having read many threads on here about not using double dots when referencing excel com objects, I decided to implement it.

It worked up until I came to doing in my loop.

Here is my loop. Note that it works if I comment this out:

        for (int i = 1; i < dgv.Columns.Count + 1; i++)
        {
            excelWorkbook.Cells[1, i] = dgv.Columns[i - 1].HeaderText;

            var cell = excelWorkbook.Cells[1, i];
            var fontSetter = cell.Font;
            fontSetter.Bold = true; //Bolds the header row

            // Garbage collecting
            GC.Collect();
            GC.WaitForPendingFinalizers();

            Marshal.FinalReleaseComObject(fontSetter);
            Marshal.FinalReleaseComObject(cell);
        }

Shouldn't my code dispose of them variables correctly?

Here is my full code:

[Code removed]

I am trying to follow the steps over at How do I properly clean up Excel interop objects? (the second answer)

Upvotes: 1

Views: 84

Answers (2)

TheGateKeeper
TheGateKeeper

Reputation: 4530

I did it by following the method specified by nightcoder in How do I properly clean up Excel interop objects?.

You don't need to reference anything and has the least clutter of them all, it closes the process by its ID. Hope this helps someone who comes in looking.

Upvotes: 0

to StackOverflow
to StackOverflow

Reputation: 124794

It's not easy to get this right. But I'm surprised the following even compiles:

excelWorkbook.Cells[1, i] = dgv.Columns[i - 1].HeaderText; 
var cell = excelWorkbook.Cells[1, i]; 

Perhaps you meant:

excelWorkbook.Cells[1, i].Value = dgv.Columns[i - 1].HeaderText; 
var cell = excelWorkbook.Cells[1, i]; 

which should be replaced by:

var cell = excelWorkbook.Cells[1, i]; 
cell.Value = dgv.Columns[i - 1].HeaderText; 

I don't see the point in your GC.Collect and GC.WaitForPendingFinalizers calls, since you make them before cell and fontSetter go out of scope.

Finally the calls to Marshal.FinalReleaseComObject should probably be in a finally block, so that they will be executed even if an Exception is thrown.

Upvotes: 1

Related Questions