Skip to content
This repository has been archived by the owner on Aug 2, 2023. It is now read-only.

Commit

Permalink
Add AutoPooled buffer example
Browse files Browse the repository at this point in the history
  • Loading branch information
benaadams committed Oct 31, 2016
1 parent da971a7 commit c441844
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 1 deletion.
62 changes: 62 additions & 0 deletions src/System.Buffers.Experimental/System/Buffers/AutoBufferPool.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
using System.Collections.Concurrent;

namespace System.Buffers
{
public class AutoBufferPool
{
private readonly static AutoBufferPool s_shared = new AutoBufferPool();
public static AutoBufferPool Shared => s_shared;

private ConcurrentQueue<AutoPooledMemory> _pool = new ConcurrentQueue<AutoPooledMemory>();

public OwnedMemory<byte> Rent(int minimumBufferSize)
{
var array = ArrayPool<byte>.Shared.Rent(minimumBufferSize);

AutoPooledMemory memory;
if (!_pool.TryDequeue(out memory))
{
memory = new AutoPooledMemory(array, this);
}
else
{
memory.Initalize(array);
}

return memory;
}

private void Return(AutoPooledMemory memory)
{
_pool.Enqueue(memory);
}

private class AutoPooledMemory : OwnedMemory<byte>
{
private AutoBufferPool _pool;

public AutoPooledMemory(byte[] array, AutoBufferPool pool) : base(array, 0, array.Length)
{
_pool = pool;
}

public void Initalize(byte[] array)
{
base.Initialize(array, 0, array.Length);
}

protected override void Dispose(bool disposing)
{
// Return Array to pool before clear
ArrayPool<byte>.Shared.Return(Array);
base.Dispose(disposing);
}

protected override void DisposeComplete()
{
// Disposal complete, no init/clear race - return AutoPooledMemory to pool
_pool.Return(this);
}
}
}
}
3 changes: 2 additions & 1 deletion src/System.Buffers.Experimental/project.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@
"System.Slices": { "target": "project" },
"System.Text.Primitives": { "target": "project" },
"System.Threading": "4.0.11",
"System.Runtime.InteropServices": "4.1.0"
"System.Runtime.InteropServices": "4.1.0",
"System.Collections.Concurrent": "4.0.12"
},
"frameworks": {
"netstandard1.1": {
Expand Down

0 comments on commit c441844

Please sign in to comment.