When is it acceptable to call GC.Collect?

前端 未结 24 2575
挽巷
挽巷 2020-11-22 08:54

The general advise is that you should not call GC.Collect from your code, but what are the exceptions to this rule?

I can only think of a few very speci

24条回答
  •  佛祖请我去吃肉
    2020-11-22 09:03

    There are some situations where it is better safe than sorry.

    Here is one situation.

    It is possible to author an unmanaged DLL in C# using IL rewrites (because there are situations where this is necessary).

    Now suppose, for example, the DLL creates an array of bytes at the class level - because many of the exported functions need access to such. What happens when the DLL is unloaded? Is the garbage collector automatically called at that point? I don't know, but being an unmanaged DLL it is entirely possible the GC isn't called. And it would be a big problem if it wasn't called. When the DLL is unloaded so too would be the garbage collector - so who is going to be responsible for collecting any possible garbage and how would they do it? Better to employ C#'s garbage collector. Have a cleanup function (available to the DLL client) where the class level variables are set to null and the garbage collector called.

    Better safe than sorry.

提交回复
热议问题