Folks,
If I set a large object to .net to null in the middle of a long-running method (not necessarily CPU intensive…just long-running) is it immediately game for garbage collection OR does the method need to complete before the object is ready for garbage collection?
The method doesn’t need to complete, but neither do you need to set the variable to null, if the GC can tell you’re not going to read from it again. For example:
The object is eligible for collection at the indicated point – assuming nothing else has kept a reference to it, of course. The important thing is whether anything is ever going to be able to read that value again. You can even assign the variable a different value and then read it, and so long as the GC knows that it won’t see the original value again, that won’t act as a GC root. For example:
Output:
In fact, it can get more extreme than that: an object can be eligible for garbage collection even while a method is running “in” it so long as the GC can detect that nothing can ever read a field again. Here’s a short but complete example:
Output:
(Run this not in the debugger – the debugger delays garbage collection so that you can still watch variables.)
One point to note: your question talks about setting an object to null… that concept doesn’t exist. You only ever set a variable to null. It’s worth distinguishing between the two.