Last active
February 24, 2017 22:52
-
-
Save floko84/e187d69f7963cacac366aa370ee7af01 to your computer and use it in GitHub Desktop.
Simple and transparent sliding timer implementation using MemoryCache, available in .NET 4+.
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
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