How to customize .NET 4.0's System.Runtime.Caching.ChangeMonitor
namespace CustomChangeMonitorDemo { public class ClipboardChangeMonitor : ChangeMonitor { #region Var private string _clipboardText; private Timer _timer; private string _uniqueID; #endregion
#region Private Property
private string m_ClipboardText
{
get { return _clipboardText ?? string.Empty; }
set
{
if (_clipboardText == value)
return;
_clipboardText = value;
OnChanged(value);
}
}
private System.Windows.Forms.Timer m_Timer
{
get
{
return _timer ?? (_timer = new System.Windows.Forms.Timer());
}
}
#endregion
#region Public Property
public override string UniqueId
{
get { return _uniqueID ?? (_uniqueID = Guid.NewGuid().ToString()); }
}
#endregion
#region Constructor
public ClipboardChangeMonitor()
{
m_Timer.Interval = 1000;
m_Timer.Tick += m_Timer_Tick;
m_Timer.Start();
_clipboardText = Clipboard.GetText();
InitializationComplete();
}
#endregion
#region Protected Method
protected override void Dispose(bool disposing)
{
}
#endregion
#region Event Process
void m_Timer_Tick(object sender, EventArgs e)
{
m_ClipboardText = Clipboard.GetText();
}
#endregion
}
}
namespace CustomChangeMonitorDemo { class Program { [STAThread] static void Main(string[] args) { FileContentProvider textFile = new FileContentProvider(); Stopwatch sw = new Stopwatch(); while (true) { sw.Reset(); sw.Start(); Console.WriteLine(textFile.Content); sw.Stop(); Console.WriteLine(“Elapsed Time: {0} ms”, sw.ElapsedMilliseconds); Console.WriteLine(new string(’=’, 50)); Console.ReadLine(); Application.DoEvents(); } } }
public class FileContentProvider
{
public String Content
{
get
{
const string CACHE_KEY = "Content";
string content = m_Cache[CACHE_KEY] as string;
if (content == null)
{
CacheItemPolicy policy = new CacheItemPolicy();
//policy.SlidingExpiration = TimeSpan.FromMilliseconds(1500);
var changeMonitor = new ClipboardChangeMonitor();
policy.ChangeMonitors.Add(changeMonitor);
content = Guid.NewGuid().ToString();
Thread.Sleep(1000);
m_Cache.Set(CACHE_KEY, content, policy);
}
return content;
}
}
private ObjectCache _cache;
private ObjectCache m_Cache
{
get
{
if (_cache == null)
_cache = MemoryCache.Default;
return _cache;
}
}
}
}