title: How can I time how long garbage collection is taking in C#?
body: <p>I would like to time how long garbage collection is taking.</p>
  
  <p>Based on these articles:</p>
  
  <ul>
  <li><a href="https://msdn.microsoft.com/en-us/library/cc713687(v=vs.110).aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/cc713687(v=vs.110).aspx</a></li>
  <li><a href="http://www.codeproject.com/Articles/101136/Garbage-Collection-Notifications-in-NET" rel="nofollow">http://www.codeproject.com/Articles/101136/Garbage-Collection-Notifications-in-NET</a></li>
  </ul>
  
  <p>I've come up with the code below. Is this the correct way to time how long garbage collection is taking in C#?</p>
  
  <pre><code>class Program
  {
      public static void Main(string[] args)
      {
          var done = false;
          var load = new List&lt;byte[]&gt;();
  
          var pollGC = new Action(() =&gt;
          {
              // Register for a notification. 
              GC.RegisterForFullGCNotification(10, 10);
              Console.WriteLine("Registered for GC notification.");
  
              Stopwatch gcTimer = new Stopwatch();
  
              while (!done)
              {
                  // Check for a notification of an approaching collection.
                  GCNotificationStatus s = GC.WaitForFullGCApproach();
                  if (s == GCNotificationStatus.Succeeded)
                  {
                      Console.WriteLine("GC is about to start.");
                      load.Clear();
                      gcTimer.Restart();
                  }
  
                  // Check for a notification of a completed collection.
                  s = GC.WaitForFullGCComplete();
                  if (s == GCNotificationStatus.Succeeded)
                  {
                      Console.WriteLine("GC has finished in {0} ms", gcTimer.ElapsedMilliseconds);
                  }
  
                  Thread.Sleep(500);
              }
              GC.CancelFullGCNotification();
  
              Console.WriteLine("Finished monitoring GC");
  
          });
  
          var doWork = new Action(() =&gt;
          {
              while (!done)
              {
                  try
                  {
                      load.Add(new byte[10000]);
                  }
                  catch (OutOfMemoryException)
                  {
                      Console.WriteLine("Out of memory. {0}", load.Count);
                  }
              }
          });
  
          Console.WriteLine(GCSettings.IsServerGC);
  
          Task.Run(pollGC);
          Task.Run(doWork);
  
          Console.ReadLine();
          done = true;
          GC.CancelFullGCNotification();
  
          Thread.Sleep(2000);
      }
  }
  </code></pre>