C#.NET — Is it possible to explicitly invoke the Garbage Collector (GC)?
-
AYes
-
BNo
-
C—
-
D—
-
E—
Answer
Correct Answer: Yes
Explanation
Introduction / Context:The .NET runtime manages memory automatically via a garbage collector. Developers sometimes wonder whether they can force a collection for testing or diagnostics, and what the implications are.
Given Data / Assumptions:
- We are considering explicit APIs versus automatic behavior.
- We focus on what is possible, not necessarily recommended.
Concept / Approach:.NET exposes APIs such as GC.Collect(), GC.GetTotalMemory(...), and GC.WaitForPendingFinalizers(). Calling GC.Collect() requests that the runtime perform a collection across generations, though the GC retains ultimate control. Explicit collection is generally discouraged in production because it can hurt performance and disrupt generational heuristics.
Step-by-Step Solution:
1) Recognize thatGC.Collect() exists and is callable.2) Understand that it is a request; timing and exact impact are runtime-managed.3) Prefer letting the GC run automatically unless you have a measured scenario (e.g., large object graph release before going idle).Verification / Alternative check:Create a small test harness, allocate objects, call GC.Collect(), and observe memory/free lists via diagnostic tools.
Why Other Options Are Wrong:
- No: Incorrect — the API is present and callable.
Common Pitfalls:Misusing explicit collections can increase pause times and degrade throughput; rely on profiling before forcing collections.
Final Answer:Yes