Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F#: Disposing of resources that are inside a closure?

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.

like image 904
FSharpN00b Avatar asked Dec 13 '10 05:12

FSharpN00b


1 Answers

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.)

like image 53
Brian Avatar answered Nov 13 '22 15:11

Brian