public void LazyCache() { var indexer = new LazyIndexer <int, InternalObject>((id) => { return(new InternalObject(id)); }); const int instanceCount = 20; Parallel.For(0, instanceCount, (id) => { //以下代码是在并发状态下运行1000次获取实例的代码,主要测试 //LazyIndexer.Init在并发状态下也能正常工作 Parallel.For(0, 1000, (j) => { var obj = indexer.Get(id); }); }); Assert.AreEqual(indexer.Keys.Length, instanceCount); var halfInstanceCount = instanceCount / 2; //减去一半 Parallel.For(0, halfInstanceCount, (id) => { Parallel.For(0, 1000, (j) => { indexer.Rmove(id); }); }); Assert.AreEqual(indexer.Keys.Length, halfInstanceCount); }
public void LazyFilter() { var indexer = new LazyIndexer <int, InternalFilterClass>((id) => { return(new InternalFilterClass(id)); }, (item) => { if (item.Number % 2 == 0) { return(false); //不保留2的倍数 } return(true); }); const int instanceCount = 20; Parallel.For(0, instanceCount, (id) => { Parallel.For(0, 20, (j) => { var obj = indexer.Get(id); }); }); foreach (var value in indexer.Values) { Assert.IsTrue(value.Number % 2 > 0); } Assert.AreEqual(indexer.Keys.Length, instanceCount / 2); for (var i = 0; i < instanceCount; i++) { var obj = _getFilterInstance(i); if (i % 2 == 0) { //由于是不缓存的项,所以两次编号不同 var obj2 = _getFilterInstance(i); Assert.AreNotEqual(obj.Id, obj2.Id); } else { //由于是缓存的项,所以两次编号相同 var obj2 = _getFilterInstance(i); Assert.AreEqual(obj.Id, obj2.Id); } } }
/// <summary> /// 使用方式: /// using(var temp = buffer.GetBytes(ByteSegmentSize.Byte256)) /// { /// var bytes = temp.Items; /// } /// </summary> /// <param name="segmentSize"></param> /// <returns></returns> private IPoolItem <ByteArray> BorrowBytes(SegmentSize segmentSize) { var pool = _pools.Get(segmentSize); return(pool.Borrow()); }