Windows C#内存不足通知

时间:2019-02-05 06:15:03

标签: c# memory-management out-of-memory

如何从c#订阅Windows内存不足通知?

我们的c#应用具有大量非托管内存分配,如果操作系统内存可用性较低,我们可以释放该内存。

1 个答案:

答案 0 :(得分:1)

使用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();
                }

            }

        }           


    }