Skip to content

Instantly share code, notes, and snippets.

@floko84
Last active February 24, 2017 22:52
Show Gist options
  • Save floko84/e187d69f7963cacac366aa370ee7af01 to your computer and use it in GitHub Desktop.
Save floko84/e187d69f7963cacac366aa370ee7af01 to your computer and use it in GitHub Desktop.
Simple and transparent sliding timer implementation using MemoryCache, available in .NET 4+.
using System;
using System.Runtime.Caching;
public class SlidingTimer
{
public EventHandler TimeoutElapsed;
private readonly ObjectCache cache;
private readonly CacheItemPolicy cacheItemPolicy;
private readonly string cacheKey;
public SlidingTimer(TimeSpan timeout)
{
this.cache = MemoryCache.Default;
this.cacheItemPolicy = new CacheItemPolicy()
{
SlidingExpiration = timeout,
RemovedCallback = CacheEntryRemoved,
};
this.cacheKey = Guid.NewGuid().ToString();
}
public void Ping()
{
var cacheItem = this.cache.GetCacheItem(this.cacheKey);
if (null == cacheItem)
{
cacheItem = new CacheItem(this.cacheKey, this);
this.cache.Set(cacheItem, this.cacheItemPolicy);
}
}
protected virtual void OnTimeoutElapsed(EventArgs e)
{
var handler = this.TimeoutElapsed;
if (null != handler)
{
handler(this, e);
}
}
private void CacheEntryRemoved(CacheEntryRemovedArguments arguments)
{
this.OnTimeoutElapsed(EventArgs.Empty);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment