Skip to content

Instantly share code, notes, and snippets.

@JCKodel
Created February 8, 2018 01:45
Show Gist options
  • Save JCKodel/02c854b3844e70e0513018e1d816265a to your computer and use it in GitHub Desktop.
Save JCKodel/02c854b3844e70e0513018e1d816265a to your computer and use it in GitHub Desktop.
Disposable Pool
using System;
namespace Pools
{
public abstract class GenericPool<T> : IDisposable where T : class
{
public abstract void Dispose();
private T _instance;
public T Instance => _instance ?? (_instance = CreateInstance());
protected abstract T CreateInstance();
public override string ToString()
{
return Instance.ToString();
}
}
}
using System.Collections.Concurrent;
using System.Text;
namespace Pools
{
public sealed class StringBuilderPool : GenericPool<StringBuilder>
{
private StringBuilderPool()
{
}
private static readonly ConcurrentQueue<StringBuilderPool> _queue = new ConcurrentQueue<StringBuilderPool>();
public static StringBuilderPool Get()
{
if(_queue.IsEmpty || _queue.TryDequeue(out var instance) == false)
{
instance = new StringBuilderPool();
}
return instance;
}
public override void Dispose()
{
Instance.Clear();
_queue.Enqueue(this);
}
protected override StringBuilder CreateInstance()
{
return new StringBuilder();
}
}
}
Usage:
using(var sbp = StringBuilderPool.Get())
{
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment