Hi this is an exmaple of how C# language handles Com interop resource management. orginal source :
Excel.Application app = null;
Excel.Workbooks books = null;
Excel.Workbook book = null;
Excel.Sheets sheets = null;
Excel.Worksheet sheet = null;
Excel.Range range = null;
try
{
app = new Excel.Application();
books = app.Workbooks;
book = books.Add();
sheets = book.Sheets;
sheet = sheets.Add();
range = sheet.Range["A1"];
range.Value = "Lorem Ipsum";
book.SaveAs(@"C:\Temp\ExcelBook" + DateTime.Now.Millisecond + ".xlsx");
book.Close();
app.Quit();
}
finally
{
if (range != null) Marshal.ReleaseComObject(range);
if (sheet != null) Marshal.ReleaseComObject(sheet);
if (sheets != null) Marshal.ReleaseComObject(sheets);
if (book != null) Marshal.ReleaseComObject(book);
if (books != null) Marshal.ReleaseComObject(books);
if (app != null) Marshal.ReleaseComObject(app);
}
Personally i think the code above is reasonable and necessary. But it is not functional or F# way. I ended up defining all these com variables at different levels of nested try... finally and try...with and because the variable has to be defined before try blocks the clean up codes exist in both the finally and with block. It is very messy.
how can i implement the same thing in F# properly? Its a little ironic there are lots of examples on the internet explaining how to use F# with interop as way of demonstrating the F# power. However none of them convers how to manage the com resource cleanup.
any advice on good pattern is appreicated.