f#中处理资源清理的函数式方法
本文关键字:函数 方法 处理 资源 | 更新日期: 2023-09-27 18:02:46
嗨,这是c#语言如何处理Com互操作资源管理的一个例子。原文:
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);
}
我个人认为上面的代码是合理的和必要的。但它不是功能性的或f#的方式。我最终在不同层次的嵌套尝试中定义了所有这些com变量。最后,试一试……由于变量必须在try块之前定义,因此清理代码同时存在于finally和With块中。它很乱。如何在f#中正确实现相同的事情?有点讽刺的是,互联网上有很多例子解释如何通过互操作来使用f#,以此来展示f#的强大功能。但是,它们都没有转换如何管理com资源清理。
您可以创建一个计算表达式,在try/catch中调用每个步骤,并在完成时在finally中释放。我们可以为create/finalize创建一个带有插件函数的构建器,这样我们就可以看到发生了什么。
type FinalizationBuilder(oncreate, onfinal) =
member __.Bind(m, f) =
oncreate(box m)
try
try
f m
with ex ->
Choice2Of2 ex.Message
finally
onfinal(box m)
member __.Return(m) = Choice1Of2 m
member __.Zero() = Choice1Of2()
然后你想要一个COM工作流,当它完成时只释放COM组件。
let com = new FinalizationBuilder(ignore, System.Runtime.InteropServices.Marshal.ReleaseComObject >> ignore)
你可以这样使用:
[<EntryPoint>]
let main _ =
com {
let! app = new Excel.Application()
let! books = app.Workbooks
let! book = books.Add()
// ...
app.Quit()
} |> ignore
0
我没有安装excel,但我可以模拟异常和打印。
let demo = new FinalizationBuilder(printfn "Created %A", printfn "Released %A")
[<EntryPoint>]
let main _ =
demo {
let! x = 1
let! y = 2
let! z = 3
return x + y + z
} |> printfn "Result: %A"
0
// Created 1
// Created 2
// Created 3
// Released 3
// Released 2
// Released 1
// Result: Choice1Of2 6
或者
[<EntryPoint>]
let main _ =
demo {
let! x = 1
let! y = 2
let! z = failwith "boom"
return x + y + z
} |> printfn "Result: %A"
0
// Created 1
// Created 2
// Released 2
// Released 1
// Result: Choice2Of2 "boom"
说了这么多,看起来这些都是不必要的。一个简单的GC.Collect(); GC.WaitForPendingFinalizers()
可以解决这个问题,而不需要任何这些:https://stackoverflow.com/a/25135685/171121