Skip to content

Instantly share code, notes, and snippets.

@Drawaes
Last active May 20, 2017 23:14
Show Gist options
  • Save Drawaes/b52ab02559ed9a614080ea4a2dad35e3 to your computer and use it in GitHub Desktop.
Save Drawaes/b52ab02559ed9a614080ea4a2dad35e3 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
namespace ConsoleApp2
{
public class ReloadingCache:IDisposable
{
private List<string> _cachedItems;
private System.Threading.Timer _timer;
private System.Threading.Mutex _mutex = new System.Threading.Mutex();
public ReloadingCache()
{
_cachedItems = MyMethodThatGivesMeTheList();
_timer = new System.Threading.Timer(state =>
{
if (_mutex.WaitOne(0))
{
try
{
System.Threading.Interlocked.Exchange(ref _cachedItems, MyMethodThatGivesMeTheList());
}
finally
{
_mutex.ReleaseMutex();
}
}
}, null, 30000, 30000);
}
public void Dispose()
{
_mutex.Dispose();
_timer.Dispose();
}
public List<string> GetListToDoWork()
{
return System.Threading.Volatile.Read(ref _cachedItems);
}
private List<string> MyMethodThatGivesMeTheList()
{
return new List<string>()
{
"Test1",
"Test2"
};
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment