Introduction
Pretty often postponed destroying of objects in .NET makes tests harder to read as you are not sure when objects are ready to be removed. Let me stress that this is not for PRODUCTION product of course. It's a really bad idea to force GC job, especially so often. But as an example - while playing with .NET Remoting objects, you might be interested to know when those are ready to be collected. This sample MemoryCleaner class runs in a separate thread and forces GC to remove object periodicaly.
Using the code
Here is code of MemoryCleaner class. Full solution with test is available in download. It was written with VS2008 but it would work for any version:
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; 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();
}
}
}