다음을 통해 공유


GC 클래스

사용하지 않는 메모리를 자동적으로 회수하는 서비스인 시스템 가비지 수집기를 제어합니다.

네임스페이스: System
어셈블리: mscorlib(mscorlib.dll)

구문

‘선언
Public NotInheritable Class GC
‘사용 방법
정적 클래스의 멤버는 클래스 인스턴스를 사용하지 않고 직접 액세스할 수 있습니다.
public static class GC
public ref class GC abstract sealed
public final class GC
public final class GC

설명

이 클래스의 메서드는 개체의 가비지가 수집되는 경우와 개체에 의해 할당된 리소스가 해제되는 경우에 영향을 줍니다. 이 클래스의 속성은 시스템에서 사용할 수 있는 메모리의 전체 양 및 개체에 할당된 메모리의 수명 구분, 즉 세대에 관한 정보를 제공합니다.

가비지 수집기는 관리되는 메모리 안에 할당된 개체를 추적하고 회수합니다. 정기적으로 가비지 수집기는 개체에 할당된 메모리 중 참조가 유효하지 않은 메모리를 회수하기 위해 가비지 수집을 수행합니다. 가비지 수집은 사용 가능한 메모리를 사용하기 위한 메모리 요청을 충족할 수 없는 경우 자동적으로 수행됩니다. 또는 응용 프로그램에서 Collect 메서드를 사용하여 가비지 수집을 강제로 수행할 수 있습니다.

가비지 수집은 다음 단계로 구성됩니다:

  1. 가비지 수집기가 관리 코드에서 참조된 관리되는 개체를 찾습니다.

  2. 가비지 수집기가 참조되지 않은 개체를 종료합니다.

  3. 가비지 수집기가 참조되지 않은 개체를 해제하고 해당 메모리를 회수합니다.

수집하는 동안, 가비지 수집기는 관리 코드 안에서 개체에 대한 하나 이상의 참조를 찾는 경우 해당 개체를 해제하지 않습니다. 하지만 가비지 수집기는 비관리 코드로부터의 개체에 대한 참조는 인식하지 못하므로 명시적으로 막지 않는 한 비관리 코드에서 단독으로 사용하고 있는 개체를 해제할 수도 있습니다. KeepAlive 메서드는 가비지 수집기가 비관리 코드 안에서 사용 중인 개체를 수집하는 것을 막는 메커니즘을 제공합니다.

관리되는 메모리 할당 이외에 가비지 수집기 구현에서는 파일 핸들 또는 데이터베이스 연결과 같이 개체가 보유한 리소스에 대한 정보를 유지하지 않습니다. 어떤 형식이 해당 형식의 인스턴스가 회수되기 전에 해제되어야 하는 관리되지 않는 리소스를 사용할 때, 해당 형식은 종료자를 구현할 수 있습니다.

대부분의 경우, 종료자는 Object.Finalize 메서드를 재정의함으로써 구현됩니다. 그리고 C# 또는 C++로 작성된 형식은 소멸자를 구현하는데 컴파일러에서 Object.Finalize의 재정의로 변경합니다. 대부분의 경우 개체에 종료자가 있을 경우 가비지 수집기는 개체를 해제하기 전에 종료자를 호출합니다. 그러나 가비지 수집기는 모든 상황에서 종료자를 호출할 필요가 없습니다. 예를 들어, SuppressFinalize 메서드는 명시적으로 종료자가 호출되지 않도록 합니다. 또한 가비지 수집기는 개체를 종결시키기 위해 특정 스레드를 사용하지 않아도 되며, 서로 참조하거나 그렇지 않을 경우 가비지 수집기에서 사용할 수 있는 개체에 대한 종료자의 호출 순서를 지키지 않아도 됩니다.

리소스가 특정 시간에 해제되어야 하는 경우 클래스는 리소스 관리 및 정리 작업을 수행하는 IDisposable.Dispose 메서드를 포함하는 IDisposable 인터페이스를 구현할 수 있습니다. Dispose를 구현하는 클래스는 클래스 계약의 일부로써 클래스 소비자가 개체를 정리하기 위해 메서드를 호출할지 여부와 호출할 시기를 지정해야 합니다. 가비지 수집기는 기본적으로 Dispose 메서드를 호출하지 않습니다. 하지만 Dispose 메서드의 구현은 가비지 수집기의 종결 작업을 사용자 지정하기 위해서 GC 클래스 안의 메서드를 호출할 수 있습니다.

가비지 수집기가 세대를 사용하여 개체의 에이징을 지원하는 것이 좋지만 반드시 필요한 것은 아닙니다. 세대는 메모리에 있는 개체의 상대적 나이를 측정하는 단위입니다. 개체의 세대 번호, 즉 나이는 개체가 속하는 세대를 나타냅니다. 더 최근에 만들어진 개체는 더 새로운 세대에 속하고 응용 프로그램 수명 주기 측면에서 더 일찍 만들어진 개체보다 더 낮은 세대 번호를 가집니다. 가장 최근 세대에 속하는 개체는 0세대에 있습니다.

구현자 참고 사항 여기서는 개체의 세 세대를 지원하도록 가비지 수집기를 구현합니다. MaxGeneration은 시스템에서 지원하는 가장 큰 세대 번호를 확인합니다. 개체 에이징을 사용하면 응용 프로그램에서 가비지 수집기에게 모든 세대를 확인하도록 요청하는 대신 특정 세대 집합을 가비지 수집의 대상으로 지정할 수 있습니다.

예제

Imports System

Namespace GCCollectInt_Example
    Class MyGCCollectClass
        Private maxGarbage As Long = 10000

        Public Shared Sub Main()
            Dim myGCCol As New MyGCCollectClass

            'Determine the maximum number of generations the system
            'garbage collector currently supports.
            Console.WriteLine("The highest generation is {0}", GC.MaxGeneration)

            myGCCol.MakeSomeGarbage()

            'Determine which generation myGCCol object is stored in.
            Console.WriteLine("Generation: {0}", GC.GetGeneration(myGCCol))

            'Determine the best available approximation of the number 
            'of bytes currently allocated in managed memory.
            Console.WriteLine("Total Memory: {0}", GC.GetTotalMemory(False))

            'Perform a collection of generation 0 only.
            GC.Collect(0)

            'Determine which generation myGCCol object is stored in.
            Console.WriteLine("Generation: {0}", GC.GetGeneration(myGCCol))

            Console.WriteLine("Total Memory: {0}", GC.GetTotalMemory(False))

            'Perform a collection of all generations up to and including 2.
            GC.Collect(2)

            'Determine which generation myGCCol object is stored in.
            Console.WriteLine("Generation: {0}", GC.GetGeneration(myGCCol))
            Console.WriteLine("Total Memory: {0}", GC.GetTotalMemory(False))
            Console.Read()

        End Sub


        Sub MakeSomeGarbage()
            Dim vt As Version

            Dim i As Integer
            For i = 0 To maxGarbage - 1
                'Create objects and release them to fill up memory
                'with unused objects.
                vt = New Version
            Next i
        End Sub
    End Class
End Namespace
using System;

namespace GCCollectIntExample
{
    class MyGCCollectClass
    {
        private const long maxGarbage = 1000;
      
        static void Main()
        {
            MyGCCollectClass myGCCol = new MyGCCollectClass();

            // Determine the maximum number of generations the system
        // garbage collector currently supports.
            Console.WriteLine("The highest generation is {0}", GC.MaxGeneration);
            
            myGCCol.MakeSomeGarbage();

            // Determine which generation myGCCol object is stored in.
            Console.WriteLine("Generation: {0}", GC.GetGeneration(myGCCol));
            
            // Determine the best available approximation of the number 
        // of bytes currently allocated in managed memory.
            Console.WriteLine("Total Memory: {0}", GC.GetTotalMemory(false));
            
            // Perform a collection of generation 0 only.
            GC.Collect(0);
            
            // Determine which generation myGCCol object is stored in.
            Console.WriteLine("Generation: {0}", GC.GetGeneration(myGCCol));
            
            Console.WriteLine("Total Memory: {0}", GC.GetTotalMemory(false));
            
            // Perform a collection of all generations up to and including 2.
            GC.Collect(2);
            
            // Determine which generation myGCCol object is stored in.
            Console.WriteLine("Generation: {0}", GC.GetGeneration(myGCCol));
            Console.WriteLine("Total Memory: {0}", GC.GetTotalMemory(false));
            Console.Read();
        }

        void MakeSomeGarbage()
        {
            Version vt;

            for(int i = 0; i < maxGarbage; i++)
            {
                // Create objects and release them to fill up memory
        // with unused objects.
                vt = new Version();
            }
        }
    }
}
using namespace System;
const long maxGarbage = 1000;
ref class MyGCCollectClass
{
public:
   void MakeSomeGarbage()
   {
      Version^ vt;
      for ( int i = 0; i < maxGarbage; i++ )
      {
         
         // Create objects and release them to fill up memory
         // with unused objects.
         vt = gcnew Version;

      }
   }

};

int main()
{
   MyGCCollectClass^ myGCCol = gcnew MyGCCollectClass;
   
   // Determine the maximum number of generations the system
   // garbage collector currently supports.
   Console::WriteLine( "The highest generation is {0}", GC::MaxGeneration );
   myGCCol->MakeSomeGarbage();
   
   // Determine which generation myGCCol object is stored in.
   Console::WriteLine( "Generation: {0}", GC::GetGeneration( myGCCol ) );
   
   // Determine the best available approximation of the number
   // of bytes currently allocated in managed memory.
   Console::WriteLine( "Total Memory: {0}", GC::GetTotalMemory( false ) );
   
   // Perform a collection of generation 0 only.
   GC::Collect( 0 );
   
   // Determine which generation myGCCol object is stored in.
   Console::WriteLine( "Generation: {0}", GC::GetGeneration( myGCCol ) );
   Console::WriteLine( "Total Memory: {0}", GC::GetTotalMemory( false ) );
   
   // Perform a collection of all generations up to and including 2.
   GC::Collect( 2 );
   
   // Determine which generation myGCCol object is stored in.
   Console::WriteLine( "Generation: {0}", GC::GetGeneration( myGCCol ) );
   Console::WriteLine( "Total Memory: {0}", GC::GetTotalMemory( false ) );
}
package GCCollectIntExample; 

import System.* ;

class MyGCCollectClass
{
    private static final long maxGarbage = 1000;

    public static void main(String[] args)
    {
        MyGCCollectClass myGCCol = new MyGCCollectClass();

        // Determine the maximum number of generations the system
        // garbage collector currently supports.
        Console.WriteLine("The highest generation is {0}", 
            System.Convert.ToString(GC.get_MaxGeneration()));
        myGCCol.MakeSomeGarbage();

        // Determine which generation myGCCol object is stored in.
        Console.WriteLine("Generation: {0}", 
            System.Convert.ToString(GC.GetGeneration(myGCCol)));

        // Determine the best available approximation of the number 
        // of bytes currently allocated in managed memory.
        Console.WriteLine("Total Memory: {0}", 
            System.Convert.ToString(GC.GetTotalMemory(false)));

        // Perform a collection of generation 0 only.
        GC.Collect(0);

        // Determine which generation myGCCol object is stored in.
        Console.WriteLine("Generation: {0}", 
            System.Convert.ToString(GC.GetGeneration(myGCCol)));
        Console.WriteLine("Total Memory: {0}", 
            System.Convert.ToString(GC.GetTotalMemory(false)));

        // Perform a collection of all generations up to and including 2.
        GC.Collect(2);

        // Determine which generation myGCCol object is stored in.
        Console.WriteLine("Generation: {0}", 
            System.Convert.ToString(GC.GetGeneration(myGCCol)));
        Console.WriteLine("Total Memory: {0}", 
            System.Convert.ToString(GC.GetTotalMemory(false)));
        Console.Read();
    } //main

    void MakeSomeGarbage()
    {
        Version vt;

        for (int i = 0; i < maxGarbage; i++) {
            // Create objects and release them to fill up memory
            // with unused objects.
            vt = new Version();
        }
    } //MakeSomeGarbage
} //MyGCCollectClass

상속 계층 구조

System.Object
  System.GC

스레드로부터의 안전성

이 형식의 모든 public static(Visual Basic의 경우 Shared) 멤버는 스레드로부터 안전합니다. 인터페이스 멤버는 스레드로부터 안전하지 않습니다.

플랫폼

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

.NET Framework에서 모든 플래폼의 모든 버전을 지원하지는 않습니다. 지원되는 버전의 목록은 시스템 요구 사항을 참조하십시오.

버전 정보

.NET Framework

2.0, 1.1, 1.0에서 지원

.NET Compact Framework

2.0, 1.0에서 지원

참고 항목

참조

GC 멤버
System 네임스페이스