Release Excel Object In My Destructor

后端 未结 3 1812
北荒
北荒 2020-12-06 02:53

I\'m writing a Excel class using Microsoft.Interropt.Excel DLL. I finish all function but I have an error in my Destructor. I Want to save all changes to my file and I want

3条回答
  •  清歌不尽
    2020-12-06 03:20

    I am not sure if I am coding something wrong--tried to follow the examples here. I found that when I take advantage of the IDisposable pattern everything works unless I need to handle workbook events.

    In my scenario the user can close the Workbook before they close the app. I have declared Excel object WithEvents and coded the WorkbookBeforeClose handler to meet the requirements.

    In this scenario I get the "COM object that has been separated from its underlying RCW cannot be used" error when I go to close my app (and I have already closed the Excel). The error is happening in the Finalize when it calls Dispose(False).

    The problem goes away if I leave the Excel object declared with events but do not code any handlers.

    In my Dispose I had to swallow the error for my Workbooks.Close and Quit as they were the statements that caused the error.

提交回复
热议问题