object GetCachedValue(string id) { if (!Cache.ContainsKey(id)) { //long running operation to fetch the value for id object value = GetTheValueForId(id); Cache.Add(id, value); } return Cache[id]; }
private List m_runningCacheIds = new List(); object GetCachedValue(string id) { if (!Cache.ContainsKey(id)) { lock (m_runningCacheIds) { if (m_runningCacheIds.Contains(id)) { // Do something to wait until the other Get is done.... } else { m_runningCacheIds.Add(id); } } //long running operation to fetch the value for id object value = GetTheValueForId(id); Cache.Add(id, value); lock (m_runningCacheIds) m_runningCacheIds.Remove(id); } return Cache[id]; }
还有一个问题就是线程在等待另一个线程时要做的是获取值。
我在那种情况下使用Mutex作为:
object GetCachedValue(string Key) { // note here that I use the key as the name of the mutex // also here you need to check that the key have no invalid charater // to used as mutex name. var mut = new Mutex(true, key); try { // Wait until it is safe to enter. mut.WaitOne(); // here you create your cache if (!Cache.ContainsKey(Key)) { //long running operation to fetch the value for id object value = GetTheValueForId(Key); Cache.Add(Key, value); } return Cache[Key]; } finally { // Release the Mutex. mut.ReleaseMutex(); } }
object GetCachedValue(string id) { if (!Cache.ContainsKey(id)) { lock (_staticObj) { if (!Cache.ContainsKey(id)) { //long running operation to fetch the value for id object value = GetTheValueForId(id); Cache.Add(id, value); } } } return Cache[id]; }