【问题标题】:windows c# low memory notificationwindows c#内存不足通知
【发布时间】:2019-06-28 22:21:12
【问题描述】:

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

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

【问题讨论】:

  • 你可以check available memory 当它很低的时候 - 做点什么。
  • 是的,我们现在这样做,每 60 秒循环一次。但是内存不足的通知肯定是理想的吗?
  • 嗯,有一个事件,在SystemEvents 中称为LowMemory,但据我所知,它已经过时了。
  • @Johnny 查询 WMI? WMI 有没有办法将内存不足的事件“推送”到应用程序?
  • @Johnny 决定使用 QueryMemoryResourceNotification 和 CreateMemoryResourceNotification 通过 PInvoke 订阅 windows 内存不足事件

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


【解决方案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();
                }

            }

        }           


    }

【讨论】:

    猜你喜欢
    • 2011-09-03
    • 1970-01-01
    • 2021-05-14
    • 2020-12-23
    • 1970-01-01
    • 1970-01-01
    • 2011-09-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多