مشاركة عبر


تجميع البيانات المهملة الإعلامات

هناك مواقف فيه كامل تجميع البيانات المهملة بوقت تشغيل اللغة العامة قد يؤثر بشكل سلبي يؤثر على الأداء. يمكن أن تكون هذه مشكلة خاصة مع الملقمات التي عملية أحجام قطر أيمن متوسط من الطلبات؛ في هذه الحالة، يؤدي تجميع البيانات المهملة طويلة مهلة طلب. لمنع مجموعة كاملة من الحدوث أثناء فترة حرجة، يمكن أن تكون إبلاغك بأن كامل تجميع البيانات المهملة يقترب وبعد ذلك اتخاذ إجراء لإعادة توجيه الحمل إلى مثيل الخادم آخر. يمكن أيضا induce مجموعة نفسك، شرط أن مثيل الملقم الحالي لا يلزم عملية الطلبات.

ملاحظةملاحظة

Th هو ميزة هو تجميع البيانات المهملة متوفر فقط عند المتزامنة هو dهوabled.تبعاً للإعدادات الافتراضية، متزامنة تجميع البيانات المهملة ممكناً إلا إذا كنت تعمل في بيئة مستضافة وتغيير مضيف تكوين نيابة عنك.تجميع البيانات المهملة المتزامنة هو عند عدم توفر خادم تجميع البيانات المهملة هو المستخدمة.Th هو لا تدعم ميزة تجميع البيانات المهملة المتزامنة وذلك لأنه يتم السماح بعمليات تخصيص ذاكرة أثناء تجميع البيانات المهملة المتزامنة هو قيد التقدم.انظر إعداد وقت التشغيل <gcConcurrent> للحصول على المعلومات حول كيفية تعطيل المتزامنة تجميع البيانات المهملة.

RegisterForFullGCNotificationregهوters طريقة لإعلام أن raهوed عند وقت التشغيل senses التي تجميع البيانات المهملة كامل هو يقترب. هناك جزءان إلى هذا إعلام: عندما الكامل تجميع البيانات المهملة approaching ومتى الكامل تجميع البيانات المهملة اكتمال.

إلى تحديد عندما تم تم رفع إعلام، استخدم WaitForFullGCApproachو WaitForFullGCCompleteالأساليب. وعادة ما تستخدم هذه الطرق في whileتكرار حلقي إلى استمرار الحصول على GCNotificationStatusالتعداد الذي يعرض حالة إعلام. إذا كانت هذه القيمة Succeeded، يمكنك القيام بما يلي:

  • استجابة إلى الحصول على إعلام مع WaitForFullGCApproachالأسلوب، يمكنك إعادة توجيه حمل العمل ومن المحتمل أن يكون induce مجموعة نفسك.

  • استجابة إلى الحصول على إعلام مع WaitForFullGCCompleteالأسلوب، يمكنك توفير مثيل الملقم الحالي إلى معالجة طلبات مرة أخرى. يمكنك أيضا جمع المعلومات. على سبيل المثال، يمكنك استخدام CollectionCountأسلوب إلى تسجيل عدد المجموعات.

WaitForFullGCApproachو WaitForFullGCCompleteصممت أساليب إلى العمل إلى gether. استخدام واحد دون الآخر أن نتائج غير معرفة.

كامل البيانات المهملة مجموعة

ويؤدي وقت التشغيل تجميع البيانات المهملة بكامل إذا تحققت أي من الحالات التالية:

  • Enough ذاكرة has been promoted في generation 2 إلى cause the التالي generation 2 مجموعة.

  • Enough ذاكرة has been promoted في the قطر أيمن متوسط كائن كومة ذاكرة مؤقتة إلى cause the التالي generation 2 مجموعة.

  • A مجموعة of generation 1 هو escalated إلى a مجموعة of generation 2 due إلى غير ذلك factors.

The thresholds you specify في the RegisterForFullGCNotification أسلوب يطبق على the أول الثاني scenarios. However, في the أول السيناريو you will not دوماً receive the إعلام at the الوقت proportional إلى the عتبة قيم you specify for الثاني reasons:

  • The وقت التشغيل does not فحص each مربع متوسط كائن تخصيص (for الأداء reasons).

  • فقط generation 1 collections يرقّي ذاكرة في generation 2.

The third السيناريو also contributes إلى the uncertainty of when you will receive the إعلام. على الرغم من أن ترتيب هو هو لا ضمان، إثبات أن طريقة مفيدة لتقليل التأثير تجميع البيانات المهملة الكامل inopportune بواسطة إعادة توجيه الطلبات أثناء th هو جمعهم الوقت أو inducing المجموعة نفسك عند ذلك يمكن أن يكون أفضل.

معلمات عتبة إعلام

RegisterForFullGCNotificationالأسلوب على معلمتين إلى تحديد قيم عتبة الكائنات الجيل 2 وكومة الذاكرة المؤقتة لكائن كبير. عند تحقيق هذه قيم، يجب أن يكون إعلام تجميع البيانات المهملة مرفوع. يصف الجدول التالي هذه المعلمات.

المعلمة

الوصف

maxGenerationThreshold

رقم بين 1 و 99 التي تعين متى يجب الإعلام مرفوع تستند إلى الكائنات ترقية في توليد 2.

largeObjectHeapThreshold

رقم بين 1 و 99 التي تعين متى يجب إعلام مرفوع تستند إلى الكائنات التي يتم تخصيصها في كومة ذاكرة مؤقتة لكائن كبير.

إذا عينت القيمة التي هو كبيرا للغاية، هناك هو احتمال عالية، سوف تتلقى إعلاماً، ولكن قد يكون طويلاً في فترة الانتظار قبل وقت التشغيل يؤدي إلى مجموعة. إذا قمت induce مجموعة بنفسك، قد يمكنك استرداد المزيد الكائنات من هو ويكون واستخلاص عن حالة وقت التشغيل يؤدي إلى المجموعة.

إذا قمت بتحديد القيمة التي هو منخفض جداً، قد يؤدي وقت التشغيل على المجموعة قبل أن كان لديك الوقت الكافي للإعلام.

المثال

الوصف

في ما يلي مثال، لمجموعة الخوادم الخدمة طلبات ويب الواردة. محاكاة حمل العمل لمعالجة طلبات، عبارة عن صفائف بايت تمت الإضافة إلى List<T>مجموعة. كل regهوters الالخادم لإعلام تجميع البيانات المهملة وثم بدء تشغيل مؤشر ترابط في WaitForFullGCProcالأسلوب مستخدم لمراقبة مستمرة GCNotificationStatusالتعداد التي هو يتم إرجاعها بواسطة WaitForFullGCApproachو WaitForFullGCCompleteالأساليب.

WaitForFullGCApproachو WaitForFullGCCompleteاستدعاء وظائف المعنية معالجة حدث المستخدم وظائفها عند إعلام هو raهوed:

  • OnFullGCApproachNotify

    وهذا أسلوب يستدعي RedirectRequestsمستخدم أسلوب، الذي يرشد الخادم الاصطفاف الطلب إلى تعليق إرسال الطلبات إلى الملقم. وهذا هو simulated ب إعداد المستوى الفئة متغير bAllocateإلى falseحيث يتم تخصيص الكائنات لا أكثر.

    التالي، FinishExistingRequestsالأسلوب مستخدم هو استدعاء لمعالجة طلبات الملقم المعلقة. finهوh وهذا هو simulated بواسطة مسح List<T>مجموعة.

    وأخيراً، تجميع البيانات المهملة هو induced لأن الضوء حمل العمل.

  • OnFullGCCompleteNotify

    Th هو أسلوب استدعاء الأسلوب مستخدم AcceptRequestsلاستئناف قبول الطلبات نظراً لأن الخادم هو لم يعد عرضه لمجموعة كاملة من البيانات المهملة. هو simulated هذا إجراء بتعيين bAllocateالمتغير إلى trueحيث يمكن كائنات سيرة ذاتية التي يتم إضافتها إلى List<T>مجموعة.

التالي تعليمات برمجية تحتوي على " 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الأسلوب مستخدم، والذي يتضمن مستمر أثناء تكرار حلقي للتحقق من وجود رسائل إعلام بواسطة تجميع البيانات المهملة.

    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;

        }
    }
}

راجع أيضًا:

موارد أخرى

تجميع البيانات المهملة.