Reputation: 12107
I have a F# object like this:
type myObject() =
...
do
// calling a 3rd party lib that will do
// callbacks into this object's methods
and, in my main initialization, I do this:
let _ = myObject()
and go on with the rest of the code.
So, this object is setting up callbacks from a 3rd party library; the callbacks are going to land in this object but the object itself will not be referenced anywhere.
Question 1: will this object survive garbage collection
Question 2: if not, how to make it permanent
Upvotes: 0
Views: 112
Reputation: 243051
I think the question whether an object assigned to a placeholder _
will remain referenced from the location where it is declared is not the important question here. The important question is whether the external library will keep a reference to the object.
For most normal libraries that I can think of this would be the case. For example, consider something like this:
let register f =
let tmr = new System.Timers.Timer(1000.)
tmr.Elapsed.Add f
tmr.Start()
type MyObject() as this =
do register this.Foo
member x.Foo(_) = printfn "hi"
let _ = MyObject()
Here, the implementation of .NET timers will need to keep a reference to all the timers that you created (so that it can trigger them) and the timer we create keeps reference to the instance of MyObject
. Regardless of whether _
creates a reference or not, the object will be referenced through the callback.
I can think of only a few ways in which you could register a callback without keeping a reference to the object - and those would most likely be by using native interop and unsafe code. If that's what you're doing, then it's better to create a global ResizeArray
somewhere in a static field and keep a reference to your object there. In all other normal cases, you don't need to worry about this.
Upvotes: 2