P
Peter Duniho
[snip]
However, you're right that parameters are treated differently from
local variables, and as long as the parameter references the instance
for the duration of the call to the method, the instance won't be
collected.
[snip]
I don't know if I'm convinced of that. You may have been right the
first time. What made you change your mind? Is there a section in
the CLI specification that talks about this?
I wrote a test myself. And just like Michael said, while I could
easily reproduce early collection for an object referenced by a local
variable, I could not get it to happen with an object referenced only
by a parameter.
Granted, it's not really a scientifically valid proof. Lack of
behavior isn't proof. But it's pretty compelling.
It is possible that the CLI _allows_ for early collection of
parameter-held references, and that the current implementation itself
just doesn't take advantage of that. But if so, the behavior is (I
think) more important than the theoretical possibility in this case,
since we're talking about what Application.Run() _does_, not what it
might do.
Obviously, a parameter can be collected during the execution of an
unmanaged function.
Based on what I've seen, I'm not convinced of that. Even when there's
no actual use of the parameter in a method, the object referenced by it
is apparently not collectable until the method returns. It wouldn't
matter whether you called a managed or unmanaged function.
That's the most important reason for the
existence of GC.KeepAlive.
I'm not sure I'd rank the reasons in that way, but I'm not willing to
quibble about which is the _most_ important. Clearly you need
GC.KeepAlive() any time you need to avoid early collection of
references that aren't explicitly used later in the method. There are
lots of different ways to run into the issue, and calling an unmanaged
function is just one example.
But if you want that to be the most important, that's okay by me.

But, I want to know if a parameter can be
collected before the completion of a managed function. I haven't seen
conclusive documentation that guarentees that it won't. In fact, I
don't see any reason why the runtime couldn't support that
optimization. Comments?
I'm not aware of any guarantee that it won't either. I can just say
that I tried very hard to get it to happen and was unable to.
Pete