GcNotification

We found 10 examples in language CSharp for this search. You will see 39 fragments of code.

Other methods

		//[Fact]TODO 这玩意怎么用
		public void GC_GCNotification()
		{
			var obj = new object();
			obj = null;
			GCNotification.GCDone += GCNotification_GCDone;
			GC.Collect();
			Thread.Sleep(TimeSpan.FromSeconds(1));
		}

// Class info from mscorlib.dll
// 
using UnityEngine;

namespace System
{
    public class GCNotificationStatus : Enum
    {
      // Fields:
  public value__ : Int32
  public Succeeded : GCNotificationStatus
  public Failed : GCNotificationStatus
  public Canceled : GCNotificationStatus
  public Timeout : GCNotificationStatus
  public NotApplicable : GCNotificationStatus
      // Properties:
      // Events:
      // Methods:
    }
}

/*
 * GCNotificationStatus.cs - Implementation of the 
 *							"System.GCNotificationStatus" enumeration.
 *
 * Copyright (C) 2009  Free Software Foundation Inc.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

namespace System
{

#if !ECMA_COMPAT && CONFIG_FRAMEWORK_2_0

[Serializable]
public enum GCNotificationStatus
{
	Succeeded		= 0,
	Failed			= 1,
	Canceled		= 2,
	Timeout			= 3,
	NotApplicable	= 4

}; // enum GCNotificationStatus

#endif // !ECMA_COMPAT && CONFIG_FRAMEWORK_2_0

}; // namespace System



        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.");
                }


                // <Snippet7>
                finalExit = true;
                checkForNotify = false;
                GC.CancelFullGCNotification();
                // </Snippet7>

            }
            catch (InvalidOperationException invalidOp)
            {

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

        // <Snippet5>
        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.");

        }
        // </Snippet5>


        // <Snippet6>
        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.");
        }
        // </Snippet6>

        // <Snippet8>
        public static void WaitForFullGCProc()
        {
            while (true)
            {
                // CheckForNotify is set to true and false in Main.
                while (checkForNotify)
                {
                    // <Snippet3>
                    // Check for a notification of an approaching collection.
                    GCNotificationStatus s = GC.WaitForFullGCApproach();
                    if (s == GCNotificationStatus.Succeeded)
                    {
                        Console.WriteLine("GC Notification 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;
                    }
                    // </Snippet3>

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


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

        }
        // </Snippet8>

        // <Snippet9>
        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();

        }

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        internal static extern int GetGCLatencyMode();

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        internal static extern int SetGCLatencyMode(int newLatencyMode);

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        internal static extern void GetMemoryInfo(out uint highMemLoadThreshold,
                                                  out ulong totalPhysicalMem,
                                                  out uint lastRecordedMemLoad,
                                                  // The next two are size_t
                                                  out UIntPtr lastRecordedHeapSize,
                                                  out UIntPtr lastRecordedFragmentation);

        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
        internal static extern int _StartNoGCRegion(long totalSize, bool lohSizeKnown, long lohSize, bool disallowFullBlockingGC);

        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
        internal static extern int _EndNoGCRegion();

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        internal static extern int GetLOHCompactionMode();

		[SecurityCritical]
		[MethodImpl(MethodImplOptions.InternalCall)]
		internal static extern int GetGCLatencyMode();
		[SecurityCritical]
		[MethodImpl(MethodImplOptions.InternalCall)]
		internal static extern void SetGCLatencyMode(int newLatencyMode);
		[SecurityCritical]
		[MethodImpl(MethodImplOptions.InternalCall)]
		private static extern int GetGenerationWR(IntPtr handle);
		[SuppressUnmanagedCodeSecurity, SecurityCritical]
		[DllImport("QCall", CharSet = CharSet.Unicode)]
		private static extern long GetTotalMemory();
		[SecurityCritical, SuppressUnmanagedCodeSecurity]
		[DllImport("QCall", CharSet = CharSet.Unicode)]
		private static extern void _Collect(int generation, int mode);
		[SecurityCritical]
		[MethodImpl(MethodImplOptions.InternalCall)]
		private static extern int GetMaxGeneration();

	public static void Register(LuaState L)
	{
		L.BeginStaticLibs("GC");
		L.RegFunction("AddMemoryPressure", AddMemoryPressure);
		L.RegFunction("RemoveMemoryPressure", RemoveMemoryPressure);
		L.RegFunction("GetGeneration", GetGeneration);
		L.RegFunction("Collect", Collect);
		L.RegFunction("CollectionCount", CollectionCount);
		L.RegFunction("KeepAlive", KeepAlive);
		L.RegFunction("WaitForPendingFinalizers", WaitForPendingFinalizers);
		L.RegFunction("SuppressFinalize", SuppressFinalize);
		L.RegFunction("ReRegisterForFinalize", ReRegisterForFinalize);
		L.RegFunction("GetTotalMemory", GetTotalMemory);
		L.RegFunction("RegisterForFullGCNotification", RegisterForFullGCNotification);
		L.RegFunction("CancelFullGCNotification", CancelFullGCNotification);
		L.RegFunction("WaitForFullGCApproach", WaitForFullGCApproach);
		L.RegFunction("WaitForFullGCComplete", WaitForFullGCComplete);
		L.RegFunction("TryStartNoGCRegion", TryStartNoGCRegion);
		L.RegFunction("EndNoGCRegion", EndNoGCRegion);
		L.RegVar("MaxGeneration", get_MaxGeneration, null);
		L.EndStaticLibs();
	}

	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static int AddMemoryPressure(IntPtr L)
	{
		try
		{
			ToLua.CheckArgsCount(L, 1);
			long arg0 = LuaDLL.tolua_checkint64(L, 1);
			System.GC.AddMemoryPressure(arg0);
			return 0;
		}
		catch (Exception e)
		{
			return LuaDLL.toluaL_exception(L, e);
		}
	}

	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static int RemoveMemoryPressure(IntPtr L)
	{
		try
		{
			ToLua.CheckArgsCount(L, 1);
			long arg0 = LuaDLL.tolua_checkint64(L, 1);
			System.GC.RemoveMemoryPressure(arg0);
			return 0;
		}
		catch (Exception e)
		{
			return LuaDLL.toluaL_exception(L, e);
		}
	}

	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static int GetGeneration(IntPtr L)
	{
		try
		{
			int count = LuaDLL.lua_gettop(L);

			if (count == 1 && TypeChecker.CheckTypes<System.WeakReference>(L, 1))
			{
				System.WeakReference arg0 = (System.WeakReference)ToLua.ToObject(L, 1);
				int o = System.GC.GetGeneration(arg0);
				LuaDLL.lua_pushinteger(L, o);
				return 1;
			}
			else if (count == 1 && TypeChecker.CheckTypes<object>(L, 1))
			{
				object arg0 = ToLua.ToVarObject(L, 1);
				int o = System.GC.GetGeneration(arg0);
				LuaDLL.lua_pushinteger(L, o);
				return 1;
			}
			else
			{
				return LuaDLL.luaL_throw(L, "invalid arguments to method: System.GC.GetGeneration");
			}
		}
		catch (Exception e)
		{
			return LuaDLL.toluaL_exception(L, e);
		}
	}

	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static int Collect(IntPtr L)
	{
		try
		{
			int count = LuaDLL.lua_gettop(L);

			if (count == 0)
			{
				System.GC.Collect();
				return 0;
			}
			else if (count == 1)
			{
				int arg0 = (int)LuaDLL.luaL_checknumber(L, 1);
				System.GC.Collect(arg0);
				return 0;
			}
			else if (count == 2)
			{
				int arg0 = (int)LuaDLL.luaL_checknumber(L, 1);
				System.GCCollectionMode arg1 = (System.GCCollectionMode)ToLua.CheckObject(L, 2, typeof(System.GCCollectionMode));
				System.GC.Collect(arg0, arg1);
				return 0;
			}
			else if (count == 3)
			{
				int arg0 = (int)LuaDLL.luaL_checknumber(L, 1);
				System.GCCollectionMode arg1 = (System.GCCollectionMode)ToLua.CheckObject(L, 2, typeof(System.GCCollectionMode));
				bool arg2 = LuaDLL.luaL_checkboolean(L, 3);
				System.GC.Collect(arg0, arg1, arg2);
				return 0;
			}
			else if (count == 4)
			{
				int arg0 = (int)LuaDLL.luaL_checknumber(L, 1);
				System.GCCollectionMode arg1 = (System.GCCollectionMode)ToLua.CheckObject(L, 2, typeof(System.GCCollectionMode));
				bool arg2 = LuaDLL.luaL_checkboolean(L, 3);
				bool arg3 = LuaDLL.luaL_checkboolean(L, 4);
				System.GC.Collect(arg0, arg1, arg2, arg3);
				return 0;
			}
			else
			{
				return LuaDLL.luaL_throw(L, "invalid arguments to method: System.GC.Collect");
			}
		}
		catch (Exception e)
		{
			return LuaDLL.toluaL_exception(L, e);
		}
	}

	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static int CollectionCount(IntPtr L)
	{
		try
		{
			ToLua.CheckArgsCount(L, 1);
			int arg0 = (int)LuaDLL.luaL_checknumber(L, 1);
			int o = System.GC.CollectionCount(arg0);
			LuaDLL.lua_pushinteger(L, o);
			return 1;
		}
		catch (Exception e)
		{
			return LuaDLL.toluaL_exception(L, e);
		}
	}

using System;
using System.Threading;

namespace OneDas.Core
{
    public static class GcNotification
    {
        private class GenObject
        {
            private int _generation;

            public GenObject(int generation)
            {
                _generation = generation;
            }

            ~GenObject()
            {
                bool flag = GC.GetGeneration(this) >= _generation;

                if (flag)
                {
                    Action<int> action = Volatile.Read<Action<int>>(ref GcNotification._GcDone);
                    bool flag2 = action != null;
                    if (flag2)
                    {
                        action(_generation);
                    }
                }

                bool flag3 = GcNotification._GcDone != null && !AppDomain.CurrentDomain.IsFinalizingForUnload() && !Environment.HasShutdownStarted;

                if (flag3)
                {
                    bool flag4 = _generation == 0;
                    if (flag4)
                    {
                        GcNotification.GenObject GenObject = new GcNotification.GenObject(0);
                    }
                    else
                    {
                        GC.ReRegisterForFinalize(this);
                    }
                }
            }
        }

        private static Action<int> _GcDone = null;
        public static event Action<int> GcDone
        {
            add
            {
                bool flag = _GcDone == null;
                if (flag)
                {
                    GcNotification.GenObject genObject = new GcNotification.GenObject(0);
                    genObject = new GcNotification.GenObject(1);
                    genObject = new GcNotification.GenObject(2);
                }
                _GcDone = (Action<int>)Delegate.Combine(_GcDone, value);
            }
            remove
            {
                _GcDone = (Action<int>)Delegate.Remove(_GcDone, value);
            }
        }
    }
}


        private static void TriggerOnceFullGarbageCollectionApproach()
        {
            OnNextFullGarbageCollectionApproach();
            OnNextFullGarbageCollectionApproach = null;
        }

        private static void TriggerOnceFullGarbageCollectionComplete()
        {
            OnNextFullGarbageCollectionComplete();
            OnNextFullGarbageCollectionComplete = null;
        }

        private static void TriggerOnceZeroGarbageCollectionComplete()
        {
            OnNextZeroGarbageCollectionComplete();
            OnNextZeroGarbageCollectionComplete = null;
        }

        private static void WaitForFullGarbageCollectionApproach()
        {
            while (true)
            {
                GCNotificationStatus notification = GC.WaitForFullGCApproach();
                if (notification == GCNotificationStatus.Succeeded)
                    OnFullGarbageCollectionApproach();
            }
        }

        private static void WaitForFullGarbageCollectionComplete()
        {
            while (true)
            {
                GCNotificationStatus notification = GC.WaitForFullGCComplete();
                if (notification == GCNotificationStatus.Succeeded)
                    OnFullGarbageCollectionComplete();
            }
        }



        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.");
                }


                // <Snippet7>
                finalExit = true;
                checkForNotify = false;
                GC.CancelFullGCNotification();
                // </Snippet7>

            }
            catch (InvalidOperationException invalidOp)
            {

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

        // <Snippet5>
        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.");

        }
        // </Snippet5>


        // <Snippet6>
        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.");
        }
        // </Snippet6>

        // <Snippet8>
        public static void WaitForFullGCProc()
        {
            while (true)
            {
                // CheckForNotify is set to true and false in Main.
                while (checkForNotify)
                {
                    // <Snippet3>
                    // Check for a notification of an approaching collection.
                    GCNotificationStatus s = GC.WaitForFullGCApproach();
                    if (s == GCNotificationStatus.Succeeded)
                    {
                        Console.WriteLine("GC Notification 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;
                    }
                    // </Snippet3>

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


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

        }
        // </Snippet8>

        // <Snippet9>
        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();

        }

Microsoft.Extensions.Internal.GcNotification : Object

Methods :

public static Void Register(Func<Object, Boolean> callback = , Object state = )
public Type GetType()
public String ToString()
public Boolean Equals(Object obj = )
public Int32 GetHashCode()

Other methods