Пример #1
0
        public static void WaitForFullGCProc()
        {
            while (true)
            {
                // Check for a notification of an approaching collection.
                GCNotificationStatus s = GC.WaitForFullGCApproach();
                if (s == GCNotificationStatus.Succeeded)
                {
                    //Console.WriteLine("GC Notification raised.");
                    events.EnqueueFront(new Event
                    {
                        Type     = "process",
                        Text     = $"Full GC Approach",
                        Tags     = new string[] { "gc" },
                        Occurred = DateTime.Now,
                    });
                }
                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.
                GCNotificationStatus status = GC.WaitForFullGCComplete();
                if (status == GCNotificationStatus.Succeeded)
                {
                    //Console.WriteLine("GC Notification raised.");
                    events.EnqueueFront(new Event
                    {
                        Type     = "process",
                        Text     = $"Full GC Complete",
                        Tags     = new string[] { "gc" },
                        Occurred = DateTime.Now,
                    });
                }
                else if (status == GCNotificationStatus.Canceled)
                {
                    //Console.WriteLine("GC Notification cancelled.");
                    break;
                }
                else
                {
                    // Could be a time out.
                    //Console.WriteLine("GC Notification not applicable.");
                    break;
                }

                Thread.Sleep(500);
            }
        }
        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 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;
                    }

                    // 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;
                    }
                }


                Thread.Sleep(500);
                // FinalExit is set to true right before
                // the main thread cancelled notification.
                if (finalExit)
                {
                    break;
                }
            }
        }
    public static void Main(string[] args)
    {
        try
        {
            // Register for a notification.
            GC.RegisterForFullGCNotification(10, 10);

            // Start a thread using WaitForFullGCProc.
            Thread startpolling = new Thread(() =>
            {
                while (true)
                {
                    // Check for a notification of an approaching collection.
                    GCNotificationStatus s = GC.WaitForFullGCApproach(1000);
                    if (s == GCNotificationStatus.Succeeded)
                    {
                        //Call event

                        Console.WriteLine("GC is about to begin");
                        GC.Collect();
                    }
                    else if (s == GCNotificationStatus.Canceled)
                    {
                        // Cancelled the Registration
                    }
                    else if (s == GCNotificationStatus.Timeout)
                    {
                        // Timeout occurred.
                    }

                    // Check for a notification of a completed collection.
                    s = GC.WaitForFullGCComplete(1000);
                    if (s == GCNotificationStatus.Succeeded)
                    {
                        //Call event
                        Console.WriteLine("GC has ended");
                    }
                    else if (s == GCNotificationStatus.Canceled)
                    {
                        //Cancelled the registration
                    }
                    else if (s == GCNotificationStatus.Timeout)
                    {
                        // Timeout occurred
                    }

                    Thread.Sleep(500);
                }
            });
            startpolling.Start();

            //Allocate huge memory to apply pressure on GC
            AllocateMemory();

            // Unregister the process
            GC.CancelFullGCNotification();
        }
        catch { }
    }
Пример #4
0
        /// <summary>
        /// Lets GC do a large collection.
        /// </summary>
        public static void CleanRAM()
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();

            GCNotificationStatus ns = GC.WaitForFullGCComplete(300);
        }
Пример #5
0
 private static void WaitForFullGarbageCollectionComplete()
 {
     while (true)
     {
         GCNotificationStatus notification = GC.WaitForFullGCComplete();
         if (notification == GCNotificationStatus.Succeeded)
         {
             OnFullGarbageCollectionComplete();
         }
     }
 }
        private static void WaitForGCThread(object arg)
        {
            const int MaxWaitMs = 10000;

            while (true)
            {
                // There is also an overload of WaitForFullGCApproach that waits indefinitely
                GCNotificationStatus status = GC.WaitForFullGCApproach(MaxWaitMs);
                bool didCollect             = false;
                switch (status)
                {
                case GCNotificationStatus.Succeeded:
                    Console.WriteLine("GC approaching!");
                    Console.WriteLine("-- redirect processing to another machine -- ");
                    didCollect = true;
                    GC.Collect();
                    break;

                case GCNotificationStatus.Canceled:
                    Console.WriteLine("GC Notification was canceled");
                    break;

                case GCNotificationStatus.Timeout:
                    Console.WriteLine("GC notification timed out");
                    break;
                }

                if (didCollect)
                {
                    do
                    {
                        status = GC.WaitForFullGCComplete(MaxWaitMs);
                        switch (status)
                        {
                        case GCNotificationStatus.Succeeded:
                            Console.WriteLine("GC completed");
                            Console.WriteLine("-- accept processing on this machine again --");
                            break;

                        case GCNotificationStatus.Canceled:
                            Console.WriteLine("GC Notification was canceled");
                            break;

                        case GCNotificationStatus.Timeout:
                            Console.WriteLine("GC completion notification timed out");
                            break;
                        }
                        // Looping isn't necessary, but it's useful if you want
                        // to check other state before waiting again.
                    } while (status == GCNotificationStatus.Timeout);
                }
            }
        }
Пример #7
0
        private static void WaitForGCThread(object arg)
        {
            const int MaxWaitMs = 10000;

            while (true)
            {
                // 无限制等待还是会让 WaitForFullGCApproach 过载
                GCNotificationStatus status = GC.WaitForFullGCApproach(MaxWaitMs);
                bool didCollect             = false;
                switch (status)
                {
                case GCNotificationStatus.Succeeded:
                    Console.WriteLine("GC approaching!");
                    Console.WriteLine("-- redirect processing to another machine --");
                    didCollect = true;
                    GC.Collect();
                    break;

                case GCNotificationStatus.Canceled:
                    Console.WriteLine("GC Notification wa canceled");
                    break;

                case GCNotificationStatus.Timeout:
                    Console.WriteLine("GC notification timed out");
                    break;
                }

                if (didCollect)
                {
                    do
                    {
                        status = GC.WaitForFullGCComplete(MaxWaitMs);
                        switch (status)
                        {
                        case GCNotificationStatus.Succeeded:
                            Console.WriteLine("GC Complete");
                            Console.WriteLine("-- accept processing on this machine again --");
                            break;

                        case GCNotificationStatus.Canceled:
                            Console.WriteLine("GC Notification was canceled");
                            break;

                        case GCNotificationStatus.Timeout:
                            Console.WriteLine("GC completion notification timed out");
                            break;
                        }
                        // 这里的循环不一定需要
                        // 但是如果你在进入下一次
                    } while (status == GCNotificationStatus.Timeout);
                }
            }
        }
Пример #8
0
        private void RegisterForGCNotifications()
        {
            Task.Factory.StartNew(() =>
            {
                GC.RegisterForFullGCNotification(10, 10);
                while (running)
                {
                    try
                    {
                        // Check for a notification of an approaching collection.
                        GCNotificationStatus s = GC.WaitForFullGCApproach();
                        if (s == GCNotificationStatus.Succeeded)
                        {
                            Add("GC is coming.  prepare yourself");
                        }
                        else if (s == GCNotificationStatus.Canceled)
                        {
                            Add("GC cancelled.  Huzzah.");
                            break;
                        }
                        else
                        {
                            Add("GC Notification not applicable");
                            break;
                        }
                        // Check for a notification of a completed collection.
                        GCNotificationStatus status = GC.WaitForFullGCComplete();
                        if (status == GCNotificationStatus.Succeeded)
                        {
                            Add("GC Complete");
                        }
                        else if (status == GCNotificationStatus.Canceled)
                        {
                            Add("GC cancelled.  Huzzah");
                            break;
                        }
                        else
                        {
                            Add("GC Notification not applicable");
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteLine(string.Format("Fudging hell {0}", ex));
                    }

                    Thread.Sleep(500);
                }
            }, TaskCreationOptions.LongRunning);
        }
Пример #9
0
        private static void TestWait(bool approach, int timeout)
        {
            GCNotificationStatus result = GCNotificationStatus.Failed;
            Thread cancelProc           = null;

            // Since we need to test an infinite (or very large) wait but the API won't return, spawn off a thread which
            // will cancel the wait after a few seconds
            //
            bool cancelTimeout = (timeout == -1) || (timeout > 10000);

            GC.RegisterForFullGCNotification(20, 20);

            try
            {
                if (cancelTimeout)
                {
                    cancelProc = new Thread(new ThreadStart(CancelProc));
                    cancelProc.Start();
                }

                if (approach)
                {
                    result = GC.WaitForFullGCApproach(timeout);
                }
                else
                {
                    result = GC.WaitForFullGCComplete(timeout);
                }
            }
            catch (Exception e)
            {
                Assert.True(false, $"({approach}, {timeout}) Error - Unexpected exception received: {e.ToString()}");
            }
            finally
            {
                if (cancelProc != null)
                {
                    cancelProc.Join();
                }
            }

            if (cancelTimeout)
            {
                Assert.True(result == GCNotificationStatus.Canceled, $"({approach}, {timeout}) Error - WaitForFullGCApproach result not Cancelled");
            }
            else
            {
                Assert.True(result == GCNotificationStatus.Timeout, $"({approach}, {timeout}) Error - WaitForFullGCApproach result not Timeout");
            }
        }
Пример #10
0
        private static void SubscribeForGCNotifications()
        {
            GC.RegisterForFullGCNotification(1, 1);

            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    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;
                    }

                    // 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;
                    }
                }
            }, TaskCreationOptions.LongRunning);
        }
Пример #11
0
        public static void MonitorGc()
        {
            GC.RegisterForFullGCNotification(10, 10);
            Thread startpolling = new Thread(() =>
            {
                while (true)
                {
                    // Check for a notification of an approaching collection.
                    GCNotificationStatus s = GC.WaitForFullGCApproach(1000);
                    if (s == GCNotificationStatus.Succeeded)
                    {
                        //Call event
                        Logger.Debug("GC is about to begin");
                        GC.Collect();
                    }
                    else if (s == GCNotificationStatus.Canceled)
                    {
                        // Cancelled the Registration
                    }
                    else if (s == GCNotificationStatus.Timeout)
                    {
                        // Timeout occurred.
                    }

                    // Check for a notification of a completed collection.
                    s = GC.WaitForFullGCComplete(1000);
                    if (s == GCNotificationStatus.Succeeded)
                    {
                        //Call event
                        Logger.Debug("GC has ended");
                    }
                    else if (s == GCNotificationStatus.Canceled)
                    {
                        //Cancelled the registration
                    }
                    else if (s == GCNotificationStatus.Timeout)
                    {
                        // Timeout occurred
                    }

                    Thread.Sleep(500);
                }
            });

            startpolling.Start();
        }
Пример #12
0
 private void WaitForFullGcProc()
 {
     while (true)
     {
         GCNotificationStatus s = GC.WaitForFullGCApproach();
         if (s == GCNotificationStatus.Succeeded)
         {
             Console.WriteLine("GC started?");
             m_stopWatch = Stopwatch.StartNew();
             s           = GC.WaitForFullGCComplete();
             if (s == GCNotificationStatus.Succeeded)
             {
                 Console.WriteLine("GC completed {0}", m_stopWatch.Elapsed);
             }
         }
         Thread.Sleep(500);
     }
 }
Пример #13
0
        public void CheckForGCNotification()
        {
            //This show up a lot. None of the documentation on GC currently seems to adjust this the way I expect it to.
            GCNotificationStatus s = GC.WaitForFullGCApproach();

            if (s == GCNotificationStatus.Succeeded)
            {
                Log.WriteLog("Garbage Collection Impeding!");
                Log.WriteLog("Gen0 collections:" + GC.CollectionCount(0), Log.VerbosityLevels.High);
                Log.WriteLog("Gen1 collections:" + GC.CollectionCount(1), Log.VerbosityLevels.High);
                Log.WriteLog("Gen2 collections:" + GC.CollectionCount(2), Log.VerbosityLevels.High);
            }

            s = GC.WaitForFullGCComplete();
            if (s == GCNotificationStatus.Succeeded)
            {
                Log.WriteLog("Garbage Collection Completed. Processing has resumed.");
            }
        }
Пример #14
0
        private void CheckGCTime()
        {
            var pollGC = new Action(() =>
            {
                // Register for a notification.
                GC.RegisterForFullGCNotification(10, 10);

                Stopwatch gcTimer = new Stopwatch();

                while (running)
                {
                    // Check for a notification of an approaching collection.
                    GCNotificationStatus s = GC.WaitForFullGCApproach();
                    if (s == GCNotificationStatus.Succeeded)
                    {
                        // GC is about to start.
                        gcTimer.Restart();
                    }

                    // Check for a notification of a completed collection.
                    s = GC.WaitForFullGCComplete();
                    if (s == GCNotificationStatus.Succeeded)
                    {
                        Interlocked.Increment(ref _lastGCTime);
                        try
                        {
                            _lastGCTime = gcTimer.ElapsedMilliseconds;
                        }
                        finally
                        {
                            Interlocked.Decrement(ref _lastGCTime);
                        }
                    }

                    Thread.Sleep(500);
                }
                // Finishing monitoring GC.
                GC.CancelFullGCNotification();
            });

            Task.Run(pollGC);
        }
Пример #15
0
 public void Watch()
 {
     GC.RegisterForFullGCNotification(50, 50);
     watcherThread = new Thread(() =>
     {
         while (true)
         {
             GCNotificationStatus status = GC.WaitForFullGCApproach();
             //Omitted error handling code here
             if (GCApproaches != null)
             {
                 GCApproaches(this, EventArgs.Empty);
             }
             status = GC.WaitForFullGCComplete();
             //Omitted error handling code here
             if (GCComplete != null)
             {
                 GCComplete(this, EventArgs.Empty);
             }
         }
     });
     watcherThread.IsBackground = true;
     watcherThread.Start();
 }
Пример #16
0
 public static void WaitForFullGCProc()
 {
     while (true)
     {
         try {
             // CheckForNotify is set to true and false in Main.
             while (checkForNotify)
             {
                 // Check for a notification of an approaching collection.
                 Console.WriteLine("GC.WaitForFullGCApproach()");
                 GCNotificationStatus s = GC.WaitForFullGCApproach();
                 Console.WriteLine($"Before GC Memory Alloced {GC.GetTotalMemory(false)}");
                 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;
                 }
                 // Check for a notification of a completed collection.
                 Console.WriteLine("GC.WaitForFullGCComplete()");
                 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;
                 }
             }
             Thread.Sleep(500);
             Console.WriteLine($"CheckForNotify: {checkForNotify}");
             // FinalExit is set to true right before
             // the main thread cancelled notification.
             if (finalExit)
             {
                 break;
             }
         } catch (Exception ex) {
             Console.WriteLine(ex.Message);
         }
     }
     Console.WriteLine($"--------------------------------Finished--------------------------------");
 }
Пример #17
0
        static void Main(string[] args)
        {
            Dictionary <int, ChainsAPM.Interfaces.ICommand <byte> > CommandList = new Dictionary <int, ICommand <byte> >();
            var cmd1 = new ChainsAPM.Commands.Common.SendString("");
            var cmd2 = new ChainsAPM.Commands.Agent.FunctionEnterQuick(0, 0, 0);
            var cmd3 = new ChainsAPM.Commands.Agent.FunctionLeaveQuick(0, 0, 0);
            var cmd4 = new ChainsAPM.Commands.Agent.AgentInformation();
            var cmd5 = new ChainsAPM.Commands.Agent.FunctionTailQuick(0, 0, 0);
            var cmd6 = new ChainsAPM.Commands.Agent.DefineFunction(0, 0, "", 0);

            CommandList.Add(cmd1.Code, cmd1);
            CommandList.Add(cmd1.Code + 1, cmd1); // SendString handles Unicode and ASCII
            CommandList.Add(cmd2.Code, cmd2);
            CommandList.Add(cmd3.Code, cmd3);
            CommandList.Add(cmd4.Code, cmd4);
            CommandList.Add(cmd5.Code, cmd5);
            CommandList.Add(cmd6.Code, cmd6);
            CallContext.LogicalSetData("CommandProviders", CommandList);
            GC.RegisterForFullGCNotification(30, 50);
            System.Runtime.GCSettings.LatencyMode = System.Runtime.GCLatencyMode.LowLatency;
            var timerCheck = new System.Threading.Thread(new System.Threading.ThreadStart(() =>
            {
                Console.WriteLine("GC Notification thread started.");
                while (true)
                {
                    GCNotificationStatus s = GC.WaitForFullGCApproach();
                    if (s == GCNotificationStatus.Succeeded)
                    {
                        Console.WriteLine("GC Notification raised.");
                        foreach (var item in concurrentAgentHandlerList)
                        {
                            item.Value.PauseTimers();
                        }
                    }
                    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(500);
                    if (s == GCNotificationStatus.Succeeded)
                    {
                        Console.WriteLine("Full GC Complete");
                        foreach (var item in concurrentAgentHandlerList)
                        {
                            item.Value.RestartTimers();
                        }
                    }
                    else if (s == GCNotificationStatus.Canceled)
                    {
                        Console.WriteLine("GC Notification cancelled.");
                        break;
                    }
                    else if (s == GCNotificationStatus.Timeout || s == GCNotificationStatus.NotApplicable)
                    {
                        foreach (var item in concurrentAgentHandlerList)
                        {
                            item.Value.RestartTimers();
                        }
                    }
                    else
                    {
                        // Could be a time out.
                        Console.WriteLine("GC Notification not applicable.");
                        break;
                    }


                    System.Threading.Thread.Sleep(500);
                    // FinalExit is set to true right before
                    // the main thread cancelled notification.
                }
            }));

            timerCheck.Name = "GC Notification Thread";
            //timerCheck.Start();
            System.Net.Sockets.TcpListener tcpListen = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Any, 8080);
            tcpListen.Start(200);
            //listenTimer = new System.Threading.Timer(TimerCallback, tcpListen, 0, 100);
            System.Threading.ThreadPool.QueueUserWorkItem(wCb, tcpListen);
            Console.WriteLine("Server started");
            Console.WriteLine("Listening on {0}", tcpListen.LocalEndpoint.ToString());
            while (true)
            {
                lock (lockConsole)
                {
                    Console.WriteLine("Current connected clients: {0}\t\tPackets: {1}", clientsConnected, messagesRecvd);
                }
                System.Threading.Thread.Sleep(1000);
            }
        }
Пример #18
0
        /// <summary>
        /// 等待完整的GC
        /// </summary>
        private static void WaitForFullGCProc()
        {
            while (true)
            {
                try
                {
                    // 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)
                        {
                            WriteLog("GC 即将开始");
                            OnFullGCApproachNotify();
                        }
                        else if (s == GCNotificationStatus.Canceled)
                        {
                            WriteLog("GC 即将开始 -> 取消");
                            break;
                        }
                        else
                        {
                            // This can occur if a timeout period
                            // is specified for WaitForFullGCApproach(Timeout)
                            // or WaitForFullGCComplete(Timeout)
                            // and the time out period has elapsed.
                            WriteLog("GC 即将开始 -> 超时");
                            break;
                        }

                        // Check for a notification of a completed collection.
                        s = GC.WaitForFullGCComplete();
                        if (s == GCNotificationStatus.Succeeded)
                        {
                            WriteLog("GC 完成");
                            OnFullGCCompleteEndNotify();
                        }
                        else if (s == GCNotificationStatus.Canceled)
                        {
                            WriteLog("GC 完成 -> 取消");
                            break;
                        }
                        else
                        {
                            // Could be a time out.
                            WriteLog("GC 完成 -> 超时");
                            break;
                        }
                    }
                }
                catch (Exception exp)
                {
                    WriteLog("GC 检查异常 -> " + exp);
                }

                Thread.Sleep(500);
                // FinalExit is set to true right before
                // the main thread cancelled notification.
                if (finalExit)
                {
                    break;
                }
            }
        }
Пример #19
0
        public static bool TestWait(bool approach, int timeout)
        {
            GCNotificationStatus result = GCNotificationStatus.Failed;
            Thread cancelProc           = null;

            // Since we need to test an infinite (or very large) wait but the API won't return, spawn off a thread which
            // will cancel the wait after a few seconds
            //
            bool cancelTimeout = (timeout == -1) || (timeout > 10000);

            GC.RegisterForFullGCNotification(20, 20);

            try
            {
                if (cancelTimeout)
                {
                    cancelProc = new Thread(new ThreadStart(CancelProc));
                    cancelProc.Start();
                }

                if (approach)
                {
                    result = GC.WaitForFullGCApproach(timeout);
                }
                else
                {
                    result = GC.WaitForFullGCComplete(timeout);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error - Unexpected exception received: {0}", e.ToString());
                return(false);
            }
            finally
            {
                if (cancelProc != null)
                {
                    cancelProc.Join();
                }
            }

            if (cancelTimeout)
            {
                if (result != GCNotificationStatus.Canceled)
                {
                    Console.WriteLine("Error - WaitForFullGCApproach result not Cancelled");
                    return(false);
                }
            }
            else
            {
                if (result != GCNotificationStatus.Timeout)
                {
                    Console.WriteLine("Error - WaitForFullGCApproach result not Timeout");
                    return(false);
                }
            }

            return(true);
        }
Пример #20
0
        static void Main(string[] arguments)
        {
            /*
             * bool isServerGC = GCSettings.IsServerGC;
             * int pointerSize = IntPtr.Size;
             * int numberProcs = Environment.ProcessorCount;
             * Console.WriteLine("{0} on {1}-bit with {2} procs",
             *  (isServerGC ? "Server" : "Workstation"),
             *  ((pointerSize == 8) ? 64 : 32),
             *  numberProcs);
             *
             * Console.WriteLine(GC.MaxGeneration);
             *
             * // Listing 15-1
             * GC.Collect(0);
             * Console.WriteLine($"{GC.CollectionCount(0)} {GC.CollectionCount(1)} {GC.CollectionCount(2)}");
             * GC.Collect(1);
             * Console.WriteLine($"{GC.CollectionCount(0)} {GC.CollectionCount(1)} {GC.CollectionCount(2)}");
             * GC.Collect(2);
             * Console.WriteLine($"{GC.CollectionCount(0)} {GC.CollectionCount(1)} {GC.CollectionCount(2)}");*/

            // Listing 15-6
            Console.WriteLine("Hello world!");
            var process = Process.GetCurrentProcess();

            Console.WriteLine($"{process.PrivateMemorySize64:N0}");
            Console.WriteLine($"{process.WorkingSet64:N0}");
            Console.WriteLine($"{process.VirtualMemorySize64:N0}");
            Console.WriteLine($"{GC.GetTotalMemory(true):N0}");
            //Console.WriteLine(process.PagedMemorySize64 / 1024);
            //Console.WriteLine(process.PagedSystemMemorySize64 / 1024);
            //Console.WriteLine(process.NonpagedSystemMemorySize64 / 1024);
            Console.ReadLine();
            //GC.Collect();
            //Console.ReadLine();

            /*
             * {
             *  var args = new object[5];
             *  var mi = typeof(GC).GetMethod("GetMemoryInfo", BindingFlags.Static | BindingFlags.NonPublic);
             *  mi.Invoke(null, args);
             *  uint highMemLoadThreshold = (uint) args[0];
             *  ulong totalPhysicalMem = (ulong) args[1];
             *  uint lastRecordedMemLoad = (uint) args[2];
             *  UIntPtr lastRecordedHeapSize = (UIntPtr) args[3];
             *  UIntPtr lastRecordedFragmentation = (UIntPtr) args[4];
             * }
             *
             * {
             *  var args = new object[2];
             *  var mi = typeof(MemoryFailPoint).GetMethod("GetMemorySettings", BindingFlags.Static | BindingFlags.NonPublic);
             *  mi.Invoke(null, args);
             * }
             *
             * // Listing 15-14
             * try
             * {
             *  using (MemoryFailPoint failPoint = new MemoryFailPoint(sizeInMegabytes: 1024))
             *  {
             *      // Do calculations
             *  }
             * }
             * catch (InsufficientMemoryException e)
             * {
             *  Console.WriteLine(e);
             *  throw;
             * }
             */
            {
                // Region 15-13
                GC.RegisterForFullGCNotification(10, 10);
                Thread startpolling = new Thread(() =>
                {
                    while (true)
                    {
                        GCNotificationStatus s = GC.WaitForFullGCApproach(1000);
                        if (s == GCNotificationStatus.Succeeded)
                        {
                            Console.WriteLine("GC is about to begin");
                        }
                        else if (s == GCNotificationStatus.Timeout)
                        {
                            continue;
                        }

                        // ...
                        // react to full GC, for example call code disabling current server from load balancer
                        // ...
                        s = GC.WaitForFullGCComplete(10_000);
                        if (s == GCNotificationStatus.Succeeded)
                        {
                            Console.WriteLine("GC has ended");
                        }
                        else if (s == GCNotificationStatus.Timeout)
                        {
                            Console.WriteLine("GC took alarming amount of time");
                        }
                    }
                });
                startpolling.Start();
                GC.CancelFullGCNotification();
            }
        }