Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

165
Views
garbage collection not working int .net c#

I am working with this code as an example:

var p = new person("Amir");
var zp = new person("Amiraa");
GC.Collect();
GC.WaitForPendingFinalizers();

class person
{
    public person(string nName)
    {
        Console.WriteLine("New");
        string name = nName;
    }

    ~person()
    {
        Console.WriteLine("Garbage collected");
    }
}

But the resault on the console only shows "New", not "Garbage collected". so why is the gc not working?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Play around, and you'll notice that your code works as expected in Release, but not necessarily Debug.

This is because the variables p and zp are still in scope at the point that you call GC.Collect(). They still refer to the person instances.

In Release, the GC will happily collect objects referenced by variables which are still in scope, so long as they are not used again. In Debug, the debugger needs to let you view the contents of all variables which are in scope, so the GC can't collect them.

If you do:

var p = new person("Amir");
var zp = new person("Amiraa");

p = null;
zp = null;

GC.Collect();
GC.WaitForPendingFinalizers();

You'll see the output you expect, even in Debug. Note that the tiered compilation introduced in .NET 6 affects this, and the above test might not work as expected.

If you introduce a separate method, so the lifetimes of p and zp are explicitly scoped, you should see the expected behaviour even on .NET 6 in Debug:

Test();
GC.Collect();
GC.WaitForPendingFinalizers();

void Test()
{
    var p = new person("Amir");
    var zp = new person("Amiraa");
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!