title: Run GC.Collect synchronously
body: <p><code>GC.Collect</code> appears to start the garbage collection in a background thread, and then return immediately. How can I run <code>GC.Collect</code> synchronously -- i.e., wait for the garbage collection to complete?</p>
  
  <p>This is in the context of NUnit tests. I tried adding the <a href="http://msdn.microsoft.com/en-us/library/at1stbec.aspx" rel="noreferrer">gcConcurrent</a> setting to my test assembly's app.config file, and I tried the same with nunit.exe.config. Neither had any effect -- when I debug, I can still see the finalizer being run on the "GC Finalizer Thread", rather than the thread that called <code>GC.Collect</code> (NUnit's "TestRunnerThread"), and both threads are running concurrently.</p>
  
  <p>Background: I want my tests to fail if they leak (don't call Dispose on) a particular class. So I've added a finalizer to that class that sets a static <code>wasLeaked</code> flag; then my test TearDown calls <code>GC.Collect()</code> and then throws if <code>wasLeaked</code> is true. But it's not failing deterministically, because when it reads <code>wasLeaked</code>, the finalizer usually hasn't even been called yet. (It fails some later test instead, after the garbage collection finally finishes.)</p>