Example #1
0
        internal static bool Check(int minFreeMemoryPercentage, bool throwOnLowMemory, out ulong availableMemoryBytes)
        {
            // Boundary check percentage, if out of bounds Gate is turned off.
            // 0 is defined as disabled. Configuration defines 99 as max allowed so we disable
            // if we receive something out of range
            availableMemoryBytes = 0;
            if (minFreeMemoryPercentage < 1 || minFreeMemoryPercentage > 99)
            {
                return(true);
            }

            UnsafeNativeMethods.MEMORYSTATUSEX memoryStatus = new UnsafeNativeMethods.MEMORYSTATUSEX();
            GetGlobalMemoryStatus(ref memoryStatus);

            if (memoryStatus.ullAvailVirtual < (memoryStatus.ullTotalVirtual / 100 * (ulong)minFreeMemoryPercentage))
            {
                availableMemoryBytes = memoryStatus.ullAvailVirtual;
            }
            else if (memoryStatus.ullAvailPhys < (memoryStatus.ullTotalPhys / 100 * (ulong)minFreeMemoryPercentage))
            {
                availableMemoryBytes = memoryStatus.ullAvailPhys;
            }

            if (TD.ServiceActivationAvailableMemoryIsEnabled())
            {
                TD.ServiceActivationAvailableMemory(availableMemoryBytes);
            }

            if (availableMemoryBytes != 0)
            {
                if (throwOnLowMemory)
                {
                    throw FxTrace.Exception.AsError(new InsufficientMemoryException(
                                                        SR.Hosting_MemoryGatesCheckFailed(availableMemoryBytes,
                                                                                          minFreeMemoryPercentage)));
                }
                else
                {
                    return(false);
                }
            }

            return(true);
        }