The example code you have posted will keep a reference to target
, probably because you have a top level binding to it (use target = new TestDisposable()
).
If you change the code to something like the below code you will see that weakTarget
is dead because the reference to target
is only local to the test()
function.
do
let test() =
use target = new TestDisposable()
new WeakReference(target)
let weakTarget = test()
GC.Collect()
GC.WaitForPendingFinalizers()
GC.WaitForFullGCComplete() |> ignore
GC.Collect()
printfn "WeakTarget is alive: %b" weakTarget.IsA
I don't know if this fixes your original problem though, as this is fairly specfic to the way you have written the example code.