Created
February 8, 2018 01:45
-
-
Save JCKodel/02c854b3844e70e0513018e1d816265a to your computer and use it in GitHub Desktop.
Disposable Pool
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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