using System;
using System.Runtime.InteropServices;
namespace Boot
{
public class GCBehavior
{
/// <summary>
/// 启动定时 GC
/// </summary>
public static void StartGCByTime()
{
//每5分钟 启动垃圾收集器
double minutes = 5;
System.Timers.Timer timer = new System.Timers.Timer(minutes * 60 * 1000);
timer.Elapsed += timer_Elapsed;
timer.Start();
}
#region 内存回收
[DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize")]
public static extern int SetProcessWorkingSetSize(IntPtr process, int minSize, int maxSize);
/// <summary>
/// 释放内存
/// </summary>
public static void ClearMemory()
{
GC.Collect();
GC.WaitForPendingFinalizers();
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
}
}
#endregion
private static void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
ClearMemory();
}
}
}
定时启动GC回收
最新推荐文章于 2023-01-14 19:25:45 发布