Consider the following contrived example:
1 public class Example
2 {
3 static CountryList countryList = new CountryList();
4
5 public void DoWork(ShoppingCart cart)
6 {
7 Method1();
8
9 Method2();
10
11 cart.DoSomething();
12 }
13
14 private void Method1()
15 {
16 var person = new Person();
17 }
18
19 private void Method2()
20 {
21 var order = new Order();
22 }
23 }
In the above example, let's say currently Method2
is being executed and when the CLR is trying to allocate memory for the call to new Order()
, it finds that GC needs to be run.
Please correct me if I am wrong about the following:
- Garbage collector suspend all activity at line # 21 and kick starts a collection and once it's done, it continues with line #21 etc.?
- When garbage collector suspends all activity at line # 21, how does it find the GC roots? Are these roots found my the current callstack? i.e does GC walk up the current callstack and find roots?
For example: I think the roots in the above program would be 'order', 'cart' and 'countryList'. At this point if GC is run the only object that is collected is the one referred by 'person' as its unreachable. Am I right about this?