Question

I have a simple sequence expression that makes use of a resource that I'd like to clean up when I'm finished:

type MyObject() =
    member this.Items =
        seq {
            use resource = ResourcePool.Get()
            let c = resource.ValueCount
            if c > 0 then
                for i in 0 .. c - 1 do
                    yield resource.GetValue i
        }

If I then use the sequence to iterate, say, half-way through the items, when will the resource be Disposed?

For example:

// ...

let foo = MyObject
let item = foo.Items |> Seq.find ( fun i -> i.Name = "name" )

// ...

Will resource be disposed after Seq.find is finished? Or do I need to reconsider my resource management strategy?

Was it helpful?

Solution

It will be disposed when the IEnumerator is disposed, regardless of how many items are enumerated. For functions in the Seq module this happens when the function exits (see tryFind as an example). GetEnumerator is rarely called directly in user code, but when it is it should be done with use instead of let.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top