定时整理内存
public class FlushMemUtil { public static void StartTimer() { #region 定时整理内存 var flushTimer = new Timer(FlushMemory); flushTimer.Change(TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(30)); #endregion } #region 定时刷新内存 /// <summary> /// 刷新内存 /// </summary> static void FlushMemory(object sender = null) { try {
GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce; //net6 GC.Collect(); GC.WaitForPendingFinalizers(); if (Environment.OSVersion.Platform == PlatformID.Win32NT) { Win32API.SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, -1, -1); }
ClearMemory();
} catch (Exception e) { LogHelper.WriteErrLog(e.Message, e); } } #endregion }
[DllImport("kernel32.dll")] internal static extern bool SetProcessWorkingSetSize(IntPtr proc, int min, int max);
[DllImport("psapi.dll")] private static extern int EmptyWorkingSet(IntPtr hwProc); /// <summary> /// 静默清理系统内存 /// </summary> public static void ClearMemorySilent() { foreach (var p in Process.GetProcesses()) { using (p) { if ((p.ProcessName.Equals("System")) && (p.ProcessName.Equals("Idle"))) { //两个系统的关键进程,不整理 continue; } try { EmptyWorkingSet(p.Handle); } catch { // ignored } } } } /// <summary> /// 静默清理系统内存 /// </summary> public static void ClearMemory() { Task.Run(() => { ClearMemorySilent(); }); }
本文来自博客园,作者:willamyao,转载请注明原文链接:https://www.cnblogs.com/robertyao/p/14788939.html
代码改变世界