public void ConcurrentAllocations() { var bufferManager = new SimpleBufferManager(); int bufferSize = bufferManager.GetDefaultBufferSize(); const int ConcurrentThreads = 16; var options = new ParallelOptions { MaxDegreeOfParallelism = ConcurrentThreads, }; // Repeat the core test multiple times to ensure the exact same // results each time (verifies the recycling behavior). for (int i = 0; i < 5; i++) { var uniqueBuffers = new HashSet <byte[]>(); Parallel.For(0, ConcurrentThreads, options, j => { byte[] buffer = bufferManager.TakeBuffer(bufferSize); Assert.AreEqual(bufferSize, buffer.Length); lock (uniqueBuffers) { Assert.AreEqual(true, uniqueBuffers.Add(buffer)); } }); Trace.TraceInformation($"Round {i} after allocation: {bufferManager}"); Assert.AreEqual(ConcurrentThreads * bufferSize, bufferManager.AllocatedBytes); Assert.AreEqual(ConcurrentThreads, uniqueBuffers.Count); Assert.AreEqual(0, bufferManager.AvailableBytes); Assert.AreEqual(1, bufferManager.BucketCount); Parallel.ForEach(uniqueBuffers, options, buffer => { bufferManager.ReturnBuffer(buffer); }); Trace.TraceInformation($"Round {i} after deallocation: {bufferManager}"); Assert.AreEqual(ConcurrentThreads * bufferSize, bufferManager.AvailableBytes); Assert.AreEqual(bufferManager.AvailableBytes, bufferManager.AllocatedBytes); Assert.AreEqual(1, bufferManager.BucketCount); } }
public void RecycleBuffer() { var bufferManager = new SimpleBufferManager(); int bufferSize = bufferManager.GetDefaultBufferSize(); for (int i = 0; i < 10; i++) { byte[] buffer = bufferManager.TakeBuffer(bufferSize); Trace.TraceInformation(bufferManager.ToString()); Assert.AreEqual(bufferSize, buffer.Length); Assert.AreEqual(bufferSize, bufferManager.AllocatedBytes); Assert.AreEqual(0, bufferManager.AvailableBytes); Assert.AreEqual(1, bufferManager.BucketCount); bufferManager.ReturnBuffer(buffer); Trace.TraceInformation(bufferManager.ToString()); Assert.AreEqual(bufferSize, bufferManager.AllocatedBytes); Assert.AreEqual(bufferSize, bufferManager.AvailableBytes); Assert.AreEqual(1, bufferManager.BucketCount); } }