Search code examples
xamarinmemory-managementf#streamdispose

F# Fabulous/Xamarin memory management, why can't I use (auto dispose) this stream?


I am getting started with Fabulous, and I have created the standard template and modified it to display a bitmap.

I am using the code provided here to generate a bitmap stream, and I am defining my view as such

let view (model: Model) dispatch =
    let strm = Bmp.Create 1000 1000 (fun row col ->
        let red = float row / float 1000
        let blue = float col / float 1000
        Color.FromRgb(red, 0.0, blue)
    )
    let img = ImageSource.FromStream(fun _ -> strm)
    View.ContentPage(
      content = View.Image(source = img)
    )

This seems to work perfectly fine, but if I change let strm to use strm, it no longer works. Why?

How is the memory being managed here, why does it not work if I use the stream so that it gets disposed as soon as it goes out of scope? Are there any memory leak issues with let in this case?


Solution

  • if I use the stream so that it gets disposed as soon as it goes out of scope?

    Yes, exactly.

    Are there any memory leak issues with let in this case?

    No worries, the GC will handle it for you.

    Now the question is: if the GC can handle all such cases, why do we still need auto dispose?

    First, for big resources, it's better to dispose them as soon as we don't use them anymore, rather than relying on the GC which will dispose the resources some time later.

    Second - more important - for sharing resources, we definitely must dispose them as soon as we don't use it anymore, so that others can access the resources.