一个开源的Asp.net2.0博客系统
- using System;
- using System.Threading;
- public class MemoryCleaner
- {
- private const int PERIOD_IN_MS = 500;
- private static int _counter;
- private Thread _thread;
- private AutoResetEvent _event = new AutoResetEvent(false);
- public MemoryCleaner()
- {
- }
- public void Start()
- {
- Stop();
- _thread = new Thread(new ThreadStart(run));
- _thread.Name = string.Format("MemoryCleaner#{0}"
- , Interlocked.Increment(ref _counter));
- _thread.IsBackground = true;
- // this makes thread to be stopped when Main thread is over
- _event.Reset();
- _thread.Start();
- }
- public void Stop()
- {
- if (_thread != null)
- {
- _event.Set();
- _thread.Join();
- _thread = null;
- }
- }
- private void run()
- {
- while (!_event.WaitOne(PERIOD_IN_MS, false))
- {
- GC.Collect();
- GC.WaitForPendingFinalizers();
- }
- }
- }