GCManager.cs 5.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Runtime;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Roslyn.Utilities;

namespace Microsoft.VisualStudio.LanguageServices.Implementation
{
    /// <summary>
    /// This class manages setting the GC mode to SustainedLowLatency.
    /// 
    /// It is safe to call from any thread, but is intended to be called from
    /// the UI thread whenever user keyboard or mouse input is received.
    /// </summary>
    internal static class GCManager
    {
        // The default delay can be overridden by setting <VS Registry>\Performance : SustainedLowLatencyDuration
        private static int s_delayMilliseconds = 0;
        private const int DefaultDelayMilliseconds = 5000;

        private static ResettableDelay s_delay;

        static GCManager()
        {
            // Allow disabling SustainedLowLatency by setting the reg key value to 0
            System.Threading.Tasks.Task.Run(() =>
            {
                using (var root = VSRegistry.RegistryRoot(__VsLocalRegistryType.RegType_UserSettings))
                {
                    if (root != null)
                    {
                        using (var key = root.OpenSubKey("Performance"))
                        {
                            const string name = "SustainedLowLatencyDuration";
                            if (key != null && key.GetValue(name) != null && key.GetValueKind(name) == Microsoft.Win32.RegistryValueKind.DWord)
                            {
                                s_delayMilliseconds = (int)key.GetValue(name, s_delayMilliseconds);
                                return;
                            }
                        }
                    }
                }

                s_delayMilliseconds = DefaultDelayMilliseconds;
            });
        }

        /// <summary>
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
        /// Turn off low latency GC mode.
        /// 
        /// if there is a pending low latency mode request, Latency mode will go back to its original status as
        /// pending request timeout. once it goes back to its original status, it will not go back to low latency mode again.
        /// </summary>
        internal static void TurnOffLowLatencyMode()
        {
            if (s_delayMilliseconds <= 0)
            {
                // if it is already turned off, we don't do anything.
                return;
            }

            // first set delay to 0 to turn it off
            s_delayMilliseconds = 0;

            // explictly call Full GC to remove impact of SustainedLowLatency
            // this is based on finding on https://github.com/dotnet/roslyn/issues/6802
            // one of reason we do this here is so that GC do compact on fragmented memory.
            // which will in return let us have bigger continuous free memory chunk.
            for (var i = 0; i < 5; i++)
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }

        /// <summary>
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
        /// Call this method to suppress expensive blocking Gen 2 garbage GCs in
        /// scenarios where high-latency is unacceptable (e.g. processing typing input).
        /// 
        /// Blocking GCs will be re-enabled automatically after a short duration unless 
        /// UseLowLatencyModeForProcessingUserInput is called again.
        /// </summary>
        internal static void UseLowLatencyModeForProcessingUserInput()
        {
            if (s_delayMilliseconds <= 0)
            {
                // The registry key to opt out of Roslyn's SustainedLowLatency is set, or
                // we haven't yet initialized the value.
                return;
            }

            var currentMode = GCSettings.LatencyMode;
            var currentDelay = s_delay;
            if (currentMode != GCLatencyMode.SustainedLowLatency)
            {
                GCSettings.LatencyMode = GCLatencyMode.SustainedLowLatency;

                // Restore the LatencyMode a short duration after the
                // last request to UseLowLatencyModeForProcessingUserInput.
                currentDelay = new ResettableDelay(s_delayMilliseconds);
                currentDelay.Task.SafeContinueWith(_ => RestoreGCLatencyMode(currentMode), TaskScheduler.Default);
                s_delay = currentDelay;
            }

            if (currentDelay != null)
            {
                currentDelay.Reset();
            }
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.GC.Collect", Justification = "We are using GCCollectionMode.Optimized and this is called on a threadpool thread.")]
        private static void RestoreGCLatencyMode(GCLatencyMode originalMode)
        {
            GCSettings.LatencyMode = originalMode;
            s_delay = null;

            // hint to the GC that if it postponed a gen 2 collection, now might be a good time to do it.
            GC.Collect(2, GCCollectionMode.Optimized);
        }
    }
}