Basic Use Bindings

Category:
Disposal
Description: The 'use' binding indicates that the IDisposable.Dispose method should be called on the object at the end of its lexical scope. In this case it closes the file deterministically.
Code:
let DisposeSample1() =
System.IO.File.WriteAllLines(@"test.txt", [| "This is a test file.";
"It is easy to read." |]);

use sr = System.IO.File.OpenText @"test.txt"
let line1 = sr.ReadLine()
let line2 = sr.ReadLine()
printfn "line1 = %s" line1
printfn "line2 = %s" line2

Execution Result:
line1 = This is a test file.
line2 = It is easy to read.

Create disposal function

Category:
Disposal
Description: Create disposal function
Code:
let DisposalSample2() = 
let createDisposable f =
{
new IDisposable with
member x.Dispose() = f()
}
let test () =
using (createDisposable (fun _ -> printfn "disposed" )) (fun _ -> printfn "inside")
test()
printfn "finished"

//--------------------------------------------------------

Execution Result:
inside
disposed
finished

Last edited Sep 12, 2011 at 11:18 PM by ttliu2000, version 1

Comments

No comments yet.