[英]windows c# low memory notification
如何從c#訂閱Windows內存不足通知?
我們的c#應用程序具有大量非托管內存分配,如果操作系統內存可用性較低,則可以釋放該內存。
使用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();
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.