Why GC.KeepAlive

Oct 25, 2010 at 12:30 AM

Hello when you create a projet with Ferpect Template you have this entry point:
public static void Main(string[] args)
using (Game game = new HiDefGame())
GameLoop gameLoop = new GameLoop(game);

game.Services.AddService(typeof(IGameLoop), gameLoop);

ScreenManager screenManager = new ScreenManager1();



I don't understand why you wrote GC.KeepAlive(game). After the instruction "game.Run();", the program will be shutdown why force the GC to keep alive an instance of game??

Oct 26, 2010 at 3:43 AM

That's not what this call does. GC.KeepAlive doesn't have any effect beyond the location of the call; and the method call itself doesn't actually do anything. It is a no-op method that is opaque to the JIT compiler (meaning it can't be optimized away).

GC.KeepAlive prevents an object from becoming unreachable before execution reaches that point. However, in this case, the enclosing using statement means GC.KeepAlive will not change anything at all. If there were no more references to game, then GC.KeepAlive would prevent the Game finalizer from being invoked until execution had returned from the Run method. That is, executing a method doesn't prevent the "this" object from being unreachable, so the finalizer can run before execution returns from Run. It's the kind of thing that leads to crazy bugs, which I hate tracking down. In this case, though, the using statement handles it, so the KeepAlive call can be removed.