using System; using System.Collections.Generic; using System.Linq; using WingServerCommon.Log; namespace WingServerCommon.Interfaces.Cache { public class CacheList where T : ICacheObject { private Dictionary _collection = new Dictionary(); private object _writeLock = new Object(); /// /// The collection count /// public int Count => _collection.Count; internal CacheList() { } /// /// Load cache from db objects /// /// the db object list internal void LoadFromDbOject(IList dbOjects) { _collection.Clear(); foreach (var dbOject in dbOjects) { Add(dbOject); } } /// /// Remove a cache record with specified document id /// /// The db collection document id internal bool Remove(string documentId) { lock (_writeLock) { if (_collection.ContainsKey(documentId)) { _collection.Remove(documentId, out var removeCache); return true; } return false; } } /// /// Remove many records from cache list; this function happened on sychronization actions /// /// internal virtual void RemoveMany(string[] ids) { lock (_writeLock) { foreach (var documentId in ids) { if (_collection.ContainsKey(documentId)) { _collection.Remove(documentId, out var removeCache); } } } } /// /// Add a cache object /// /// internal void Add(T cacheObj) { if (cacheObj != null && !string.IsNullOrWhiteSpace(cacheObj.Code)) { lock (_writeLock) { var documentId = cacheObj.Code; var result = _collection.TryAdd(documentId, cacheObj); if (!result) { Logger.WriteLineError($"Add failed with id:{documentId}"); //throw new InvalidOperationException($"Add failed with id:{documentId}"); } } } } /// /// Get cache with specified document id /// /// the document id, the code in db /// /// internal T Get(string documentId) { if (_collection.ContainsKey(documentId)) { return _collection[documentId]; } return default(T); } /// /// Find values whith filters /// /// /// internal IList Where(Func predicate) { return _collection.Values.Where(predicate)?.ToList() ?? new List(); } } }