Suppose I create a closure over a resource such as a StreamWriter:
let currentdir = Directory.GetCurrentDirectory()
let testfile = sprintf "%s\\%s" currentdir "closuretest.txt"
let getwriter() =
let writer = new StreamWriter(testfile, false)
(fun() -> writer.Write "test")
Is there a way to close the StreamWriter when I'm done with the closure? Or do I need to replace the closure with a wrapper object that has a Write() method and a Dispose() method? (This is of course a trivialized example.) Thanks all.
Yes, you should to replace the closure with an IDisposable
object with a method and a Dispose()
. (Alternatively, return a tuple of closures, the second of which calls Close()
or whatnot, and leave it to the caller like that.)
(While you're at it, System.IO.Path.Combine()
should be used, rather than glueing together filenames with string formatting.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With