我正在寻找可以从两侧访问的并发集合。我想实现以下目标:
- 一些生产者添加项目
- 客户端应该能够显示最后 n 个生产的项目
- 集合应仅包含最近 x 小时内生成的元素
所以我需要访问列表的顶部 (FIFO) 以显示最后的 n 个项目,但我还需要访问列表的末尾 (LIFO) 以修剪早于 <连续 em>x 小时。
最佳答案
另一种方法是使用 MemoryCache
类,它是线程安全的,并提供用于删除“过期”项目的内置功能。</p>
我创建了一个类来保存保存的值和时间戳
public class SavedItem<T>
{
public DateTime Timestamp { get; set; }
public T Value { get; set; }
}
Collection 类将有两种方法:一种用于添加,一种用于检索 N 量的最后一项
public class ExpiredCollection
{
private readonly MemoryCache _cache;
private readonly int _hoursLimit;
public ExpiredCollection(int hoursLimit)
{
_cache = new MemoryCache("sample");
_hoursLimit = hoursLimit;
}
public void Add<T>(T value)
{
var item = CreateCacheItem(value);
var policy = CreateItemPolicy();
_cache.Add(item, policy);
}
private CacheItem CreateCacheItem<T>(T value)
{
var addedValue = new SavedItem<T>
{
Timestamp = DateTime.Now,
Value = value
};
// Create unique key to satisfy MemoryCache contract
var uniqueKey = Guid.NewGuid().ToString();
return new CacheItem(uniqueKey, addedValue);
}
private CacheItemPolicy CreateItemPolicy()
{
// This will set a time when item will be removed from the cache
var expirationTime = DateTime.Now.AddHours(_hoursLimit);
var offset = new DateTimeOffset(expirationTime);
return new CacheItemPolicy
{
AbsoluteExpiration = offset
};
}
public IEnumerable<T> GetLast<T>(int amount)
{
return _cache.Select(pair => (SavedItem<T>)pair.Value)
.OrderBy(item => item.Timestamp)
.Select(item => item.Value)
.Take(amount);
}
}
关于c# - 结合 ConcurrentQueue 和 ConcurrentStack,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50113299/