Windows的C#低内存通知

问题描述 投票:0回答:1

如何订阅到Windows内存不足的通知从C#?

我们的C#应用​​程序拥有大量非托管内存分配,这要是OS内存可用性低,我们可以免费。

c# memory-management out-of-memory
1个回答
2
投票

使用CreateMemoryResourceNotification和QueryMemoryResourceNotification检查内存状态

    enum MemoryResourceNotificationType : int
    {
        LowMemoryResourceNotification = 0,
        HighMemoryResourceNotification = 1,
    }

    [DllImport("kernel32.dll", SetLastError = true)]
    static extern IntPtr CreateMemoryResourceNotification(MemoryResourceNotificationType notificationType);

    [DllImport("kernel32.dll", SetLastError = true)]
    internal static extern bool QueryMemoryResourceNotification(IntPtr resourceNotificationHandle, out int resourceState);

    private static IntPtr MemoryResourceNotificationHandle;

    public static void TryReclaim()
    {
        MemoryResourceNotificationHandle = CreateMemoryResourceNotification(MemoryResourceNotificationType.LowMemoryResourceNotification);

        int sleepIntervalInMs = ReclaimIntervalInSeconds * 1000;

        while (true)
        {
            Thread.Sleep(10_000);

            bool isSuccecced = QueryMemoryResourceNotification(MemoryResourceNotificationHandle, out int memoryStatus);

            if (isSuccecced)
            {
                if (memoryStatus >= 1)
                {
                   DoReclaim();
                }

            }

        }           


    }
© www.soinside.com 2019 - 2024. All rights reserved.