C# program to force an immediate garbage collection (GC.Collect() Method)

C# GC.Collect Method: Here, we are going to learn how to force an immediate garbage collection in C#.Net?
Submitted by Nidhi, on May 24, 2021

The Collect() method of the GC class is used to execute garbage collection forcefully.

Syntax:

    void  GC.Collect(int genNum);

Parameter(s):

  • genNum: The number of the oldest generation to be garbage collected.

Return value:

It does not return any value.

Program:

The source code to force an immediate garbage collection is given below. The given program is compiled and executed successfully.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Program pObj = new Program();
            GC.Collect(0);

            Console.WriteLine("Garbage collection done forcefully");
            Console.WriteLine();
        }
    }
}

Output:

Garbage collection done forcefully

Press any key to continue . . .

C# Garbage Collection (GC Class) Programs »


ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.