Reclaiming memory
Since our microservice is about memory, let's create a simple routine to invoke the garbage collector, reclaim memory, and then report the results back to us. We will start by using our Start
method to create a timer that will trigger every 60 seconds:
public bool Start([CanBeNull] HostControl host) { base.Start(host); hc = host; const double interval = 60000; _timer = new Timer(interval); _timer.Elapsed += OnTick; Console.WriteLine(string.Intern("MemoryMicroService Started.")); return (true); }
The method that our timer calls is the OnTick
method. Each time this triggers, we will, in turn, call our ReclaimMemory
function, which will invoke the garbage collector and reclaim memory. After it has completed this, it will report back memory both before and after collection, as well as the garbage collection count for each generation:
protected virtual void OnTick(object sender, ElapsedEventArgs e) { Console.WriteLine(string.Intern("Reclaiming Memory")); ReclaimMemory(); } ///...