Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Something like this might suit your needs.</p> <pre><code>/// &lt;summary&gt; /// Represents a pool of objects with a size limit. /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;The type of object in the pool.&lt;/typeparam&gt; public sealed class ObjectPool&lt;T&gt; : IDisposable where T : new() { private readonly int size; private readonly object locker; private readonly Queue&lt;T&gt; queue; private int count; /// &lt;summary&gt; /// Initializes a new instance of the ObjectPool class. /// &lt;/summary&gt; /// &lt;param name="size"&gt;The size of the object pool.&lt;/param&gt; public ObjectPool(int size) { if (size &lt;= 0) { const string message = "The size of the pool must be greater than zero."; throw new ArgumentOutOfRangeException("size", size, message); } this.size = size; locker = new object(); queue = new Queue&lt;T&gt;(); } /// &lt;summary&gt; /// Retrieves an item from the pool. /// &lt;/summary&gt; /// &lt;returns&gt;The item retrieved from the pool.&lt;/returns&gt; public T Get() { lock (locker) { if (queue.Count &gt; 0) { return queue.Dequeue(); } count++; return new T(); } } /// &lt;summary&gt; /// Places an item in the pool. /// &lt;/summary&gt; /// &lt;param name="item"&gt;The item to place to the pool.&lt;/param&gt; public void Put(T item) { lock (locker) { if (count &lt; size) { queue.Enqueue(item); } else { using (item as IDisposable) { count--; } } } } /// &lt;summary&gt; /// Disposes of items in the pool that implement IDisposable. /// &lt;/summary&gt; public void Dispose() { lock (locker) { count = 0; while (queue.Count &gt; 0) { using (queue.Dequeue() as IDisposable) { } } } } } </code></pre> <p><strong>Example Usage</strong></p> <pre><code>public class ThisObject { private readonly ObjectPool&lt;That&gt; pool = new ObjectPool&lt;That&gt;(100); public void ThisMethod() { var that = pool.Get(); try { // Use that .... } finally { pool.Put(that); } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload