Does garbage collection happen at the process level or appdomain level?

后端 未结 2 896
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-07 18:58

FullGC normaly pauses all Threads while running. Having two AppDomains, each running several threads. When GC runs, will all threads be paused, or only those of either one A

2条回答
  •  误落风尘
    2021-01-07 19:37

    Hard to answer, best thing to do is just test it:

    using System;
    using System.Reflection;
    
    public class Program : MarshalByRefObject {
        static void Main(string[] args) {
            var dummy1 = new object();
            var dom = AppDomain.CreateDomain("test");
            var obj = (Program)dom.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, typeof(Program).FullName);
            obj.Test();
            Console.WriteLine("Primary appdomain, collection count = {0}, gen = {1}",
                GC.CollectionCount(0), GC.GetGeneration(dummy1));
            Console.ReadKey();
    
        }
        public void Test() {
            var dummy2 = new object();
            for (int test = 0; test < 3; ++test) {
                GC.Collect();
                GC.WaitForPendingFinalizers();
            } 
            Console.WriteLine("In appdomain '{0}', collection count = {1}, gen = {2}",
                AppDomain.CurrentDomain.FriendlyName, GC.CollectionCount(0),
                GC.GetGeneration(dummy2));
        }
    }
    

    Output:

    In appdomain 'test', collection count = 3, gen = 2
    Primary appdomain, collection count = 3, gen = 2
    

    Good evidence that a GC affects all AppDomains on the default CLR host. This surprised me.

提交回复
热议问题