項(xiàng)目比較大有時(shí)候會(huì)比較卡,雖然有GC自動(dòng)清理機(jī)制,但是還是有不盡人意的地方。所以嘗試在項(xiàng)目啟動(dòng)文件中,手動(dòng)寫了一個(gè)定時(shí)器,定時(shí)清理內(nèi)存,加快項(xiàng)目運(yùn)行速度。
public class Program  {    [DllImport("psapi.dll")]    static extern int EmptyWorkingSet(IntPtr hwProc); //清理內(nèi)存相關(guān)   static void Main()    {      //啟動(dòng)定時(shí)清理內(nèi)存      SetTimer();    }       /// <summary>    /// 定時(shí)清理內(nèi)存    /// </summary>    private static void SetTimer()    {      System.Timers.Timer aTimer = new System.Timers.Timer(); //初始化定時(shí)器      aTimer.Interval = 60000;//配置時(shí)間1分鐘      aTimer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimedEvent);      aTimer.AutoReset = true;//每到指定時(shí)間Elapsed事件是到時(shí)間就觸發(fā)      aTimer.Enabled = true; //指示 Timer 是否應(yīng)引發(fā) Elapsed 事件。    }//定時(shí)器觸發(fā)的處理事件private static void OnTimedEvent(Object source, ElapsedEventArgs e)    {      //清理內(nèi)存      GC.Collect();      GC.WaitForPendingFinalizers();      Process[] processes = Process.GetProcesses();      foreach (Process process in processes)      {        //以下系統(tǒng)進(jìn)程沒有權(quán)限,所以跳過,防止出錯(cuò)影響效率。         if ((process.ProcessName == "System") && (process.ProcessName == "Idle"))          continue;        try        {          EmptyWorkingSet(process.Handle);        }        catch        {        }      }    }}以上所述是小編給大家介紹的C#中的System.Timers.Timer定時(shí)器的使用和定時(shí)自動(dòng)清理內(nèi)存應(yīng)用,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)武林網(wǎng)網(wǎng)站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選