Last active
May 20, 2017 23:14
-
-
Save Drawaes/b52ab02559ed9a614080ea4a2dad35e3 to your computer and use it in GitHub Desktop.
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.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