载入中,请稍候……

后台线程定期执行GC.Collect()

Admin 于 2008-09-29 03:04:53 发表.NET

订阅: http://www.miniboke.com/Feed/Article_57.aspx
引用: http://www.miniboke.com/Trackback/CVgmWPuAVTHJzxobwhcQ.aspx (UTF-8)
通过反射调用private方法 < 后台线程定期执行GC.Collect() > 通过查询文本文件流前导符判断文本编码[C#]

  1. using System; 
  2. using System.Threading; 
  3. public class MemoryCleaner 
  4.     private const int PERIOD_IN_MS = 500; 
  5.  
  6.     private static int _counter; 
  7.  
  8.     private Thread _thread; 
  9.     private AutoResetEvent _event = new AutoResetEvent(false); 
  10.  
  11.     public MemoryCleaner() 
  12.     { 
  13.     } 
  14.  
  15.     public void Start() 
  16.     { 
  17.         Stop(); 
  18.         _thread = new Thread(new ThreadStart(run)); 
  19.         _thread.Name = string.Format("MemoryCleaner#{0}" 
  20.                             , Interlocked.Increment(ref _counter)); 
  21.         _thread.IsBackground = true;  
  22.         // this makes thread to be stopped when Main thread is over 
  23.         _event.Reset(); 
  24.         _thread.Start(); 
  25.     } 
  26.  
  27.     public void Stop() 
  28.     { 
  29.         if (_thread != null
  30.         { 
  31.             _event.Set(); 
  32.             _thread.Join(); 
  33.             _thread = null
  34.         } 
  35.     } 
  36.  
  37.     private void run() 
  38.     { 
  39.         while (!_event.WaitOne(PERIOD_IN_MS, false)) 
  40.         { 
  41.             GC.Collect(); 
  42.             GC.WaitForPendingFinalizers(); 
  43.         } 
  44.     } 
被阅901次, 0投一票
  • 看完了要说点啥么?
  • 昵称 (不填说不了话)
  • 信箱地址 (不会被公开,但是不填也说不了话)
  • 网址 (这个不填也成)

Powered by MiniBoke v2.0.0.8 Build 0828

Copyright © 2008 迷你博客. All rights reserved.

粤ICP备07500939号