-->

Why does FxCop flag GC.KeepAlive() as a violation?

2019-07-18 19:59发布

问题:

what is so bad about GC.KeepAlive() that FxCop flags this as a violation?

回答1:

Probably because it's considered bad practice to be calling it, just like it's a generally a bad idea to call GC.Collect -- it has generally negative consequences on the collector and/or is a possible indication of a design flaw on your end.

You should be able to reconfigured FxCop to not consider calls to the method a problem if you need to call it, however. There are valid reasons to do so, after all.



回答2:

It's not that GC.KeepAlive is particularly bad, but rather that it's not necessary if you convert to SafeHandle usage, and you really, really ought to convert to SafeHandle usage. If you're not sure why, you might want to consider taking a look at http://blogs.msdn.com/b/bclteam/archive/2005/03/16/396900.aspx and http://blogs.msdn.com/b/bclteam/archive/2006/06/23/644343.aspx.