Created
February 9, 2015 13:55
-
-
Save yemrekeskin/7f31ba87438a7ad2dd50 to your computer and use it in GitHub Desktop.
GcMemoryMonitor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var tester = new CachedMemoryMonitor(new GcMemoryMonitor(), 5); | |
Console.ReadLine(); | |
} | |
} | |
public interface IMemoryMonitor | |
: IDisposable | |
{ | |
int GetCurrentUsageAsMb(); | |
} | |
public class GcMemoryMonitor | |
: IMemoryMonitor | |
{ | |
public virtual int GetCurrentUsageAsMb() | |
{ | |
return Convert.ToInt32(GC.GetTotalMemory(false) / (1024 * 1024)); | |
} | |
public void Dispose() | |
{ | |
//do nothing | |
} | |
} | |
public class CachedMemoryMonitor | |
: IMemoryMonitor, IDisposable | |
{ | |
IMemoryMonitor _memoryMonitor; | |
Timer _usageRefreshTimer; | |
int _cachedCurrentUsageInMb; | |
public CachedMemoryMonitor(IMemoryMonitor memoryMonitor, int cacheExpirationInSeconds) | |
{ | |
if (memoryMonitor == null) | |
throw new ArgumentNullException("memoryMonitor"); | |
if (cacheExpirationInSeconds < 1) | |
cacheExpirationInSeconds = 5; | |
_memoryMonitor = memoryMonitor; | |
UpdateCurrentUsageValue(); | |
// check this out in (cacheExpirationInSeconds * 1000) | |
_usageRefreshTimer = new Timer(cacheExpirationInSeconds * 1000); | |
_usageRefreshTimer.Elapsed += (sender, e) => UpdateCurrentUsageValue(); | |
_usageRefreshTimer.Start(); | |
} | |
protected virtual void UpdateCurrentUsageValue() | |
{ | |
int oldUsage = _cachedCurrentUsageInMb; | |
_cachedCurrentUsageInMb = _memoryMonitor.GetCurrentUsageAsMb(); | |
} | |
public virtual int GetCurrentUsageAsMb() | |
{ | |
return _cachedCurrentUsageInMb; | |
} | |
public void Dispose() | |
{ | |
_usageRefreshTimer.Stop(); | |
_usageRefreshTimer.Dispose(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment