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