On Mar 5, 6:38 am, "Atmapuri" <d...@community.nospamwrote:
Hi!
I was looking at the details of how KeepAlive
works to handle my unmanaged code interop.
Several question came up. Assuming I have:
public Test2(Object a)
{
}
public Test()
{
a = new MyObject();
Test2(a);
}
Is the call to Test2 the same as the call to GC.KeepAlive?
A call to any method usually behaves the same way as GC.KeepAlive.
But, in this particular case the JIT compiler could inline Test2,
determine that it has no side-effects on 'a', and make the new
MyObject eligible for collection even before 'a' is assigned.
Can GC collect the object while one of its methods is executing,
if the object is not referenced within that method and after?
Yes. An object can be collected while one of it's methods is
executing. It may seem counter intuitive, but it's perfectly safe
(assuming all code is managed of course) if the method doesn't
reference its owner (eg. extracting an instance variable from the
'this' pointer).
>
If Inside Test2 I make a reference to "a", can GC collect
the "a" immadiately after the reference, or only after Test2 finishes?
I don't know if the GC makes a distinction between method parameters
and other variables on the stack. But, I suspect it would be eligible
after it's last use like other local variables.
>
Does the behaviour change if I write:
public Test()
{
Test2(new MyObject());
}
I don't think the behavior would be any different from your first
example.