Share via


가비지 수집 알림

업데이트: 2008년 7월

공용 언어 런타임에서 전체 가비지 수집을 실행하면 성능이 저하될 수 있는 경우가 있습니다. 특히 많은 요청을 처리하는 서버에서 이러한 경우가 나타날 수 있으며, 가비지 수집이 오래 걸려 요청 시간이 초과될 수 있습니다. 전체 가비지 수집이 임박했다는 알림을 받은 다음 작업 부하를 다른 서버 인스턴스로 리디렉션하면 중요한 작업이 수행되는 동안 전체 수집이 발생하지 않게 할 수 있습니다. 현재 서버 인스턴스에서 요청을 처리할 필요가 없을 때 수집을 직접 실행할 수도 있습니다.

참고:

이 기능은 동시 가비지 수집이 해제된 경우에만 사용할 수 있습니다. 구성이 변경된 호스트에서 호스팅되는 실행 환경이 아니면 기본적으로 동시 가비지 수집이 사용됩니다. 서버 가비지 수집이 사용되는 경우에는 동시 가비지 수집을 사용할 수 없습니다. 동시 가비지 수집이 진행되는 동안에는 메모리를 할당할 수 있으므로 이 기능은 동시 가비지 수집을 지원하지 않습니다. 동시 가비지 수집을 해제하는 방법에 대한 자세한 내용은 <gcConcurrent> 런타임 설정을 참조하십시오.

RegisterForFullGCNotification 메서드는 전체 가비지 수집이 임박했음을 런타임이 감지할 때 발생하는 알림을 수신 등록합니다. 이 알림에는 전체 가비지 수집이 임박한 시점과 전체 가비지 수집이 완료된 시점이라는 두 부분이 있습니다.

알림이 발생한 시점을 확인하려면 WaitForFullGCApproachWaitForFullGCComplete 메서드를 사용합니다. 일반적으로 while 루프에서 이러한 메서드를 사용하여 알림의 상태를 보여 주는 GCNotificationStatus 열거형을 계속 가져옵니다. 이 값이 Succeeded이면 다음을 수행할 수 있습니다.

  • WaitForFullGCApproach 메서드로 가져온 알림에 대한 응답으로 작업 부하를 리디렉션하고 수집을 직접 실행할 수 있습니다.

  • WaitForFullGCComplete 메서드로 가져온 알림에 대한 응답으로 현재 서버 인스턴스에서 요청을 처리하도록 다시 허용할 수 있습니다. 정보를 수집할 수도 있습니다. 예를 들어 CollectionCount 메서드를 사용하여 수집 횟수를 기록할 수 있습니다.

WaitForFullGCApproachWaitForFullGCComplete 메서드는 함께 작동하도록 설계되었습니다. 둘 중 하나만 사용하면 명확하지 않은 결과가 나타날 수 있습니다.

전체 가비지 수집

다음 시나리오에 하나라도 해당하면 런타임에서 전체 가비지 수집을 실행합니다.

  • 다음 2세대 수집을 유발하기에 충분한 메모리가 2세대로 승격된 경우

  • 다음 2세대 수집을 유발하기에 충분한 메모리가 대형 개체 힙으로 승격된 경우

  • 1세대 수집이 기타 요소로 인해 2세대 수집으로 에스컬레이션된 경우

RegisterForFullGCNotification 메서드에 지정하는 임계값은 처음 두 시나리오에 적용됩니다. 그러나 첫 번째 시나리오에서는 다음 두 가지 이유로 인해 임계값에 해당하는 시점에 알림을 받지 못할 수도 있습니다.

  • 런타임은 성능상의 이유로 모든 소형 개체 할당을 검사하지 않습니다.

  • 1세대 수집만 메모리를 2세대로 승격합니다.

세 번째 시나리오도 알림을 받는 시점을 명확하지 않게 합니다. 항상 그러한 것은 아니지만, 해당 시간 동안 요청을 리디렉션하거나 보다 여유가 있는 적절한 시점에 수집을 직접 실행하면 부적절한 전체 가비지 수집의 영향을 줄일 수 있습니다.

알림 임계값 매개 변수

RegisterForFullGCNotification 메서드에는 2세대 개체와 대형 개체 힙의 임계값을 지정하는 두 매개 변수가 있습니다. 이러한 값에 도달하면 가비지 수집 알림이 발생합니다. 다음 표에서는 이러한 매개 변수를 보여 줍니다.

매개 변수

설명

maxGenerationThreshold

2세대로 승격된 개체에 따라 알림을 발생시킬 시점을 지정하는 1에서 99 사이의 숫자입니다.

largeObjectHeapThreshold

대형 개체 힙에 할당된 개체에 따라 알림을 발생시킬 시점을 지정하는 1에서 99 사이의 숫자입니다.

너무 높은 값을 지정하면 알림을 받을 확률은 높아지지만 런타임에서 수집을 실행할 때까지 너무 오래 기다려야 할 수 있습니다. 수집을 직접 실행하는 경우에는 런타임에서 수집을 실행할 때보다 많은 개체를 회수해야 할 수 있습니다.

너무 낮은 값을 지정하면 사용자가 알림을 받기 전에 런타임에서 수집을 실행할 수도 있습니다.

예제

설명

다음 예제에서는 들어오는 웹 요청을 서버 그룹에서 처리합니다. 요청을 처리하는 작업 부하를 시뮬레이션하기 위해 List<T> 컬렉션에 바이트 배열이 추가되었습니다. 각 서버는 가비지 수집 알림을 수신 등록한 다음 WaitForFullGCProc 사용자 메서드에서 스레드를 시작하여 WaitForFullGCApproachWaitForFullGCComplete 메서드에서 반환하는 GCNotificationStatus 열거형을 계속 모니터링합니다.

알림이 발생하면 WaitForFullGCApproachWaitForFullGCComplete 메서드는 해당 이벤트 처리 사용자 메서드를 호출합니다.

  • OnFullGCApproachNotify

    이 메서드는 해당 서버에 대한 요청 전송을 일시 중단하도록 요청 대기 서버에 지시하는 RedirectRequests 사용자 메서드를 호출합니다. 개체가 더 이상 할당되지 않도록 클래스 수준 변수인 bAllocate를 false로 설정하여 이 동작을 시뮬레이션합니다.

    다음으로 FinishExistingRequests 사용자 메서드를 호출하여 대기 중인 서버 요청의 처리를 마칩니다. List<T> 컬렉션의 내용을 지워 이 동작을 시뮬레이션합니다.

    마지막으로 작업 부하가 감소했으므로 가비지 수집을 실행합니다.

  • OfFullGCCompeteNotify

    서버에서 전체 가비지 수집이 더 이상 실행되지 않으므로 이 메서드는 사용자 메서드인 AcceptRequests를 호출하여 요청 수신을 다시 시작합니다. List<T> 컬렉션에 개체가 다시 추가되도록 bAllocate 변수를 true로 설정하여 이 동작을 시뮬레이션합니다.

다음 코드에는 예제의 Main 메서드가 들어 있습니다.

' Variables for continual checking in the
' While loop in the WaitForFullGcProc method.
Private Shared checkForNotify As Boolean = False

' Variable for suspending work 
' (such as servicing allocated server requests)
' after a notification is received and then 
' resuming allocation after inducing a garbage collection.
Private Shared bAllocate As Boolean = False

' Variable for ending the example.
Private Shared finalExit As Boolean = False

' Collection for objects that  
' simulate the server request workload.
Private Shared load As New List(Of Byte())


Public Shared Sub Main(ByVal args() As String)
    Try
        ' Register for a notification. 
        GC.RegisterForFullGCNotification(10, 10)
        Console.WriteLine("Registered for GC notification.")

        bAllocate = True
        checkForNotify = True

        ' Start a thread using WaitForFullGCProc.
        Dim thWaitForFullGC As Thread = _
            New Thread(New ThreadStart(AddressOf WaitForFullGCProc))
        thWaitForFullGC.Start()

        ' While the thread is checking for notifications in
        ' WaitForFullGCProc, create objects to simulate a server workload.
        Try
            Dim lastCollCount As Integer = 0
            Dim newCollCount As Integer = 0


            While (True)
                If bAllocate = True Then

                    load.Add(New Byte(1000) {})
                    newCollCount = GC.CollectionCount(2)
                    If (newCollCount <> lastCollCount) Then
                        ' Show collection count when it increases:
                        Console.WriteLine("Gen 2 collection count: {0}", _
                                          GC.CollectionCount(2).ToString)
                        lastCollCount = newCollCount
                    End If

                    ' For ending the example (arbitrary).
                    If newCollCount = 500 Then
                        finalExit = True
                        checkForNotify = False
                        bAllocate = False
                        Exit While
                    End If

                End If
            End While

        Catch outofMem As OutOfMemoryException
            Console.WriteLine("Out of memory.")
        End Try

        finalExit = True
        checkForNotify = False
        GC.CancelFullGCNotification()

    Catch invalidOp As InvalidOperationException
        Console.WriteLine("GC Notifications are not supported while concurrent GC is enabled." _
                          & vbLf & invalidOp.Message)
    End Try
End Sub

// Variable for continual checking in the 
// While loop in the WaitForFullGCProc method.
static bool checkForNotify = false;

// Variable for suspending work 
// (such servicing allocated server requests)
// after a notification is received and then 
// resuming allocation after inducing a garbage collection.
static bool bAllocate = false;

// Variable for ending the example.
static bool finalExit = false;

// Collection for objects that  
// simulate the server request workload.
static List<byte[]> load = new List<byte[]>();


public static void Main(string[] args)
{
    try
    {
        // Register for a notification. 
        GC.RegisterForFullGCNotification(10, 10);
        Console.WriteLine("Registered for GC notification.");

        checkForNotify = true;
        bAllocate = true;

        // Start a thread using WaitForFullGCProc.
        Thread thWaitForFullGC = new Thread(new ThreadStart(WaitForFullGCProc));
        thWaitForFullGC.Start();

        // While the thread is checking for notifications in
        // WaitForFullGCProc, create objects to simulate a server workload.
        try
        {

            int lastCollCount = 0;
            int newCollCount = 0;


            while (true)
            {
                if (bAllocate)
                {
                    load.Add(new byte[1000]);
                    newCollCount = GC.CollectionCount(2);
                    if (newCollCount != lastCollCount)
                    {
                        // Show collection count when it increases:
                        Console.WriteLine("Gen 2 collection count: {0}", GC.CollectionCount(2).ToString());
                        lastCollCount = newCollCount;
                    }

                    // For ending the example (arbitrary).
                    if (newCollCount == 500)
                    {
                        finalExit = true;
                        checkForNotify = false;
                        break;
                    }
                }
            }

        }
        catch (OutOfMemoryException)
        {
            Console.WriteLine("Out of memory.");
        }


        finalExit = true;
        checkForNotify = false;
        GC.CancelFullGCNotification();

    }
    catch (InvalidOperationException invalidOp)
    {

        Console.WriteLine("GC Notifications are not supported while concurrent GC is enabled.\n"
            + invalidOp.Message);
    }
}

다음 코드에는 WaitForFullGCProc 사용자 메서드가 들어 있으며, 여기에는 가비지 수집 알림을 확인하는 연속적인 while 루프가 포함되어 있습니다.

Public Shared Sub WaitForFullGCProc()

    While True
        ' CheckForNotify is set to true and false in Main.

        While checkForNotify
            ' Check for a notification of an approaching collection.
            Dim s As GCNotificationStatus = GC.WaitForFullGCApproach
            If (s = GCNotificationStatus.Succeeded) Then
                Console.WriteLine("GC Notifiction raised.")
                OnFullGCApproachNotify()
            ElseIf (s = GCNotificationStatus.Canceled) Then
                Console.WriteLine("GC Notification cancelled.")
                Exit While
            Else
                ' This can occur if a timeout period
                ' is specified for WaitForFullGCApproach(Timeout) 
                ' or WaitForFullGCComplete(Timeout)  
                ' and the time out period has elapsed. 
                Console.WriteLine("GC Notification not applicable.")
                Exit While
            End If

            ' Check for a notification of a completed collection.
            s = GC.WaitForFullGCComplete
            If (s = GCNotificationStatus.Succeeded) Then
                Console.WriteLine("GC Notifiction raised.")
                OnFullGCCompleteEndNotify()
            ElseIf (s = GCNotificationStatus.Canceled) Then
                Console.WriteLine("GC Notification cancelled.")
                Exit While
            Else
                ' Could be a time out.
                Console.WriteLine("GC Notification not applicable.")
                Exit While
            End If

        End While
        Thread.Sleep(500)
        ' FinalExit is set to true right before  
        ' the main thread cancelled notification.
        If finalExit Then
            Exit While
        End If

    End While
End Sub

public static void WaitForFullGCProc()
{
    while (true)
    {
        // CheckForNotify is set to true and false in Main.
        while (checkForNotify)
        {
            // Check for a notification of an approaching collection.
            GCNotificationStatus s = GC.WaitForFullGCApproach();
            if (s == GCNotificationStatus.Succeeded)
            {
                Console.WriteLine("GC Notifiction raised.");
                OnFullGCApproachNotify();
            }
            else if (s == GCNotificationStatus.Canceled)
            {
                Console.WriteLine("GC Notification cancelled.");
                break;
            }
            else
            {
                // This can occur if a timeout period
                // is specified for WaitForFullGCApproach(Timeout) 
                // or WaitForFullGCComplete(Timeout)  
                // and the time out period has elapsed. 
                Console.WriteLine("GC Notification not applicable.");
                break;
            }

            // Check for a notification of a completed collection.
            s = GC.WaitForFullGCComplete();
            if (s == GCNotificationStatus.Succeeded)
            {
                Console.WriteLine("GC Notifiction raised.");
                OnFullGCCompleteEndNotify();
            }
            else if (s == GCNotificationStatus.Canceled)
            {
                Console.WriteLine("GC Notification cancelled.");
                break;
            }
            else
            {
                // Could be a time out.
                Console.WriteLine("GC Notification not applicable.");
                break;
            }
        }


        Thread.Sleep(500);
        // FinalExit is set to true right before  
        // the main thread cancelled notification.
        if (finalExit)
        {
            break;
        }
    }

}

다음 코드에는 아래 메서드에서 호출하는 OnFullGCApproachNotify 메서드가 들어 있습니다.

WaitForFullGCProc 메서드

Public Shared Sub OnFullGCApproachNotify()
    Console.WriteLine("Redirecting requests.")

    ' Method that tells the request queuing  
    ' server to not direct requests to this server. 
    RedirectRequests()

    ' Method that provides time to 
    ' finish processing pending requests. 
    FinishExistingRequests()

    ' This is a good time to induce a GC collection
    ' because the runtime will induce a ful GC soon.
    ' To be very careful, you can check precede with a
    ' check of the GC.GCCollectionCount to make sure
    ' a full GC did not already occur since last notified.
    GC.Collect()
    Console.WriteLine("Induced a collection.")
End Sub

public static void OnFullGCApproachNotify()
{

    Console.WriteLine("Redirecting requests.");

    // Method that tells the request queuing  
    // server to not direct requests to this server. 
    RedirectRequests();

    // Method that provides time to 
    // finish processing pending requests. 
    FinishExistingRequests();

    // This is a good time to induce a GC collection
    // because the runtime will induce a full GC soon.
    // To be very careful, you can check precede with a
    // check of the GC.GCCollectionCount to make sure
    // a full GC did not already occur since last notified.
    GC.Collect();
    Console.WriteLine("Induced a collection.");

}

다음 코드에는 아래 메서드에서 호출하는 OnFullGCApproachComplete 메서드가 들어 있습니다.

WaitForFullGCProc 메서드

Public Shared Sub OnFullGCCompleteEndNotify()
    ' Method that informs the request queuing server
    ' that this server is ready to accept requests again.
    AcceptRequests()
    Console.WriteLine("Accepting requests again.")
End Sub

public static void OnFullGCCompleteEndNotify()
{
    // Method that informs the request queuing server
    // that this server is ready to accept requests again.
    AcceptRequests();
    Console.WriteLine("Accepting requests again.");
}

다음 코드에는 OnFullGCApproachNotify 및 OnFullGCCompleteNotify 메서드에서 호출하는 사용자 메서드가 들어 있습니다. 이 사용자 메서드는 요청을 리디렉션하고 기존 요청을 완료한 다음 전체 가비지 수집이 수행된 후 요청을 다시 시작합니다.

private static void RedirectRequests()
{
    // Code that sends requests
    // to other servers.

    // Suspend work.
    bAllocate = false;

}

private static void FinishExistingRequests()
{
    // Code that waits a period of time
    // for pending requests to finish.

    // Clear the simulated workload.
    load.Clear();

}

private static void AcceptRequests()
{
    // Code that resumes processing
    // requests on this server.

    // Resume work.
    bAllocate = true;

}

전체 코드 샘플은 다음과 같습니다.

Imports System
Imports System.Collections.Generic
Imports System.Threading
Imports Microsoft.VisualBasic



Class Program


    ' Variables for continual checking in the
    ' While loop in the WaitForFullGcProc method.
    Private Shared checkForNotify As Boolean = False

    ' Variable for suspending work 
    ' (such as servicing allocated server requests)
    ' after a notification is received and then 
    ' resuming allocation after inducing a garbage collection.
    Private Shared bAllocate As Boolean = False

    ' Variable for ending the example.
    Private Shared finalExit As Boolean = False

    ' Collection for objects that  
    ' simulate the server request workload.
    Private Shared load As New List(Of Byte())


    Public Shared Sub Main(ByVal args() As String)
        Try
            ' Register for a notification. 
            GC.RegisterForFullGCNotification(10, 10)
            Console.WriteLine("Registered for GC notification.")

            bAllocate = True
            checkForNotify = True

            ' Start a thread using WaitForFullGCProc.
            Dim thWaitForFullGC As Thread = _
                New Thread(New ThreadStart(AddressOf WaitForFullGCProc))
            thWaitForFullGC.Start()

            ' While the thread is checking for notifications in
            ' WaitForFullGCProc, create objects to simulate a server workload.
            Try
                Dim lastCollCount As Integer = 0
                Dim newCollCount As Integer = 0


                While (True)
                    If bAllocate = True Then

                        load.Add(New Byte(1000) {})
                        newCollCount = GC.CollectionCount(2)
                        If (newCollCount <> lastCollCount) Then
                            ' Show collection count when it increases:
                            Console.WriteLine("Gen 2 collection count: {0}", _
                                              GC.CollectionCount(2).ToString)
                            lastCollCount = newCollCount
                        End If

                        ' For ending the example (arbitrary).
                        If newCollCount = 500 Then
                            finalExit = True
                            checkForNotify = False
                            bAllocate = False
                            Exit While
                        End If

                    End If
                End While

            Catch outofMem As OutOfMemoryException
                Console.WriteLine("Out of memory.")
            End Try

            finalExit = True
            checkForNotify = False
            GC.CancelFullGCNotification()

        Catch invalidOp As InvalidOperationException
            Console.WriteLine("GC Notifications are not supported while concurrent GC is enabled." _
                              & vbLf & invalidOp.Message)
        End Try
    End Sub

    Public Shared Sub OnFullGCApproachNotify()
        Console.WriteLine("Redirecting requests.")

        ' Method that tells the request queuing  
        ' server to not direct requests to this server. 
        RedirectRequests()

        ' Method that provides time to 
        ' finish processing pending requests. 
        FinishExistingRequests()

        ' This is a good time to induce a GC collection
        ' because the runtime will induce a ful GC soon.
        ' To be very careful, you can check precede with a
        ' check of the GC.GCCollectionCount to make sure
        ' a full GC did not already occur since last notified.
        GC.Collect()
        Console.WriteLine("Induced a collection.")
    End Sub

    Public Shared Sub OnFullGCCompleteEndNotify()
        ' Method that informs the request queuing server
        ' that this server is ready to accept requests again.
        AcceptRequests()
        Console.WriteLine("Accepting requests again.")
    End Sub

    Public Shared Sub WaitForFullGCProc()

        While True
            ' CheckForNotify is set to true and false in Main.

            While checkForNotify
                ' Check for a notification of an approaching collection.
                Dim s As GCNotificationStatus = GC.WaitForFullGCApproach
                If (s = GCNotificationStatus.Succeeded) Then
                    Console.WriteLine("GC Notifiction raised.")
                    OnFullGCApproachNotify()
                ElseIf (s = GCNotificationStatus.Canceled) Then
                    Console.WriteLine("GC Notification cancelled.")
                    Exit While
                Else
                    ' This can occur if a timeout period
                    ' is specified for WaitForFullGCApproach(Timeout) 
                    ' or WaitForFullGCComplete(Timeout)  
                    ' and the time out period has elapsed. 
                    Console.WriteLine("GC Notification not applicable.")
                    Exit While
                End If

                ' Check for a notification of a completed collection.
                s = GC.WaitForFullGCComplete
                If (s = GCNotificationStatus.Succeeded) Then
                    Console.WriteLine("GC Notifiction raised.")
                    OnFullGCCompleteEndNotify()
                ElseIf (s = GCNotificationStatus.Canceled) Then
                    Console.WriteLine("GC Notification cancelled.")
                    Exit While
                Else
                    ' Could be a time out.
                    Console.WriteLine("GC Notification not applicable.")
                    Exit While
                End If

            End While
            Thread.Sleep(500)
            ' FinalExit is set to true right before  
            ' the main thread cancelled notification.
            If finalExit Then
                Exit While
            End If

        End While
    End Sub

    Private Shared Sub RedirectRequests()
        ' Code that sends requests
        ' to other servers.

        ' Suspend work.
        bAllocate = False
    End Sub

    Private Shared Sub FinishExistingRequests()
        ' Code that waits a period of time
        ' for pending requests to finish.

        ' Clear the simulated workload.
        load.Clear()

    End Sub

    Private Shared Sub AcceptRequests()
        ' Code that resumes processing
        ' requests on this server.

        ' Resume work.
        bAllocate = True
    End Sub
End Class
using System;
using System.Collections.Generic;
using System.Threading;

namespace GCNotify
{
    class Program
    {

        // Variable for continual checking in the 
        // While loop in the WaitForFullGCProc method.
        static bool checkForNotify = false;

        // Variable for suspending work 
        // (such servicing allocated server requests)
        // after a notification is received and then 
        // resuming allocation after inducing a garbage collection.
        static bool bAllocate = false;

        // Variable for ending the example.
        static bool finalExit = false;

        // Collection for objects that  
        // simulate the server request workload.
        static List<byte[]> load = new List<byte[]>();


        public static void Main(string[] args)
        {
            try
            {
                // Register for a notification. 
                GC.RegisterForFullGCNotification(10, 10);
                Console.WriteLine("Registered for GC notification.");

                checkForNotify = true;
                bAllocate = true;

                // Start a thread using WaitForFullGCProc.
                Thread thWaitForFullGC = new Thread(new ThreadStart(WaitForFullGCProc));
                thWaitForFullGC.Start();

                // While the thread is checking for notifications in
                // WaitForFullGCProc, create objects to simulate a server workload.
                try
                {

                    int lastCollCount = 0;
                    int newCollCount = 0;


                    while (true)
                    {
                        if (bAllocate)
                        {
                            load.Add(new byte[1000]);
                            newCollCount = GC.CollectionCount(2);
                            if (newCollCount != lastCollCount)
                            {
                                // Show collection count when it increases:
                                Console.WriteLine("Gen 2 collection count: {0}", GC.CollectionCount(2).ToString());
                                lastCollCount = newCollCount;
                            }

                            // For ending the example (arbitrary).
                            if (newCollCount == 500)
                            {
                                finalExit = true;
                                checkForNotify = false;
                                break;
                            }
                        }
                    }

                }
                catch (OutOfMemoryException)
                {
                    Console.WriteLine("Out of memory.");
                }


                finalExit = true;
                checkForNotify = false;
                GC.CancelFullGCNotification();

            }
            catch (InvalidOperationException invalidOp)
            {

                Console.WriteLine("GC Notifications are not supported while concurrent GC is enabled.\n"
                    + invalidOp.Message);
            }
        }




        public static void OnFullGCApproachNotify()
        {

            Console.WriteLine("Redirecting requests.");

            // Method that tells the request queuing  
            // server to not direct requests to this server. 
            RedirectRequests();

            // Method that provides time to 
            // finish processing pending requests. 
            FinishExistingRequests();

            // This is a good time to induce a GC collection
            // because the runtime will induce a full GC soon.
            // To be very careful, you can check precede with a
            // check of the GC.GCCollectionCount to make sure
            // a full GC did not already occur since last notified.
            GC.Collect();
            Console.WriteLine("Induced a collection.");

        }


        public static void OnFullGCCompleteEndNotify()
        {
            // Method that informs the request queuing server
            // that this server is ready to accept requests again.
            AcceptRequests();
            Console.WriteLine("Accepting requests again.");
        }

        public static void WaitForFullGCProc()
        {
            while (true)
            {
                // CheckForNotify is set to true and false in Main.
                while (checkForNotify)
                {
                    // Check for a notification of an approaching collection.
                    GCNotificationStatus s = GC.WaitForFullGCApproach();
                    if (s == GCNotificationStatus.Succeeded)
                    {
                        Console.WriteLine("GC Notifiction raised.");
                        OnFullGCApproachNotify();
                    }
                    else if (s == GCNotificationStatus.Canceled)
                    {
                        Console.WriteLine("GC Notification cancelled.");
                        break;
                    }
                    else
                    {
                        // This can occur if a timeout period
                        // is specified for WaitForFullGCApproach(Timeout) 
                        // or WaitForFullGCComplete(Timeout)  
                        // and the time out period has elapsed. 
                        Console.WriteLine("GC Notification not applicable.");
                        break;
                    }

                    // Check for a notification of a completed collection.
                    s = GC.WaitForFullGCComplete();
                    if (s == GCNotificationStatus.Succeeded)
                    {
                        Console.WriteLine("GC Notifiction raised.");
                        OnFullGCCompleteEndNotify();
                    }
                    else if (s == GCNotificationStatus.Canceled)
                    {
                        Console.WriteLine("GC Notification cancelled.");
                        break;
                    }
                    else
                    {
                        // Could be a time out.
                        Console.WriteLine("GC Notification not applicable.");
                        break;
                    }
                }


                Thread.Sleep(500);
                // FinalExit is set to true right before  
                // the main thread cancelled notification.
                if (finalExit)
                {
                    break;
                }
            }

        }

        private static void RedirectRequests()
        {
            // Code that sends requests
            // to other servers.

            // Suspend work.
            bAllocate = false;

        }

        private static void FinishExistingRequests()
        {
            // Code that waits a period of time
            // for pending requests to finish.

            // Clear the simulated workload.
            load.Clear();

        }

        private static void AcceptRequests()
        {
            // Code that resumes processing
            // requests on this server.

            // Resume work.
            bAllocate = true;

        }
    }
}

참고 항목

기타 리소스

가비지 수집

변경 기록

날짜

변경 내용

이유

2008년 7월

항목이 추가되었습니다.

SP1 기능 변경