Question

I am trying to wrap an Excel.ApplicationClass in an IDisposable interface, to make it automatically close after usage. What I have is something like the following:

module Excel =
    type Application() =
        member private this.excel = new Excel.ApplicationClass()

        interface IDisposable with
            member this.Dispose() =
                this.excel.Quit()
                Marshal.ReleaseComObject(this.excel) |> ignore

When I call it in a function like

let func =
    use ex = new Excel.Application()
    ()

Two instances of Excel are started (I can see in my task manager), but only one of them is closed again. Can anyone tell me what I'm doing wrong here?

Was it helpful?

Solution

Your this.excel property creates a new Excel process each time it is evaluated, so calling Dispose creates one process and then quits it immediately, and another process just for calling Marshal.ReleaseComObject on. That second one is probably the one that is staying alive.

Change your code to something like this:

module Excel =
    type Application() =
        let m_excel = new Excel.ApplicationClass()

        member private this.excel = m_excel

        interface IDisposable with
            member this.Dispose() =
                this.excel.Quit()
                Marshal.ReleaseComObject(this.excel) |> ignore
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top