C# - Garbage Collection

前端 未结 9 831
闹比i
闹比i 2021-01-31 11:15

Ok so I understand about the stack and the heap (values live on the Stack, references on the Heap).

When I declare a new instance of a Class, this lives on the heap, wit

9条回答
  •  佛祖请我去吃肉
    2021-01-31 11:48

    Your understanding of Garbage Collection is good enough. Essentially, an unreferenced instance is deemed as being out-of-scope and no longer needed. Having determined this, the collector will remove an unreferenced object at some future point.

    There's no way to force the Garbage Collector to collect just a specific instance. You can ask it to do its normal "collect everything possible" operation GC.Collect(), but you shouldn't.; the garbage-collector is efficient and effective if you just leave it to its own devices.

    In particular it excels at collecting objects which have a short lifespan, just like those that are created as temporary objects. You shouldn't have to worry about creating loads of objects in a loop, unless they have a long lifespan that prevents immediate collection.

提交回复
热议问题