title: Unordered thread-safe collection to use as a pool?
body: <p>I created a pool class that when asked, finds or initializes an item and return it to the caller. I use a <code>ConcurrentQueue&lt;T&gt;</code> as the underlying collection but I'm not sure whether it's the right type to use.</p>
  
  <p>I don't need the items to be in any specific order, all I need is a thread-safe collection I can push to and pop from. Does .NET have a fast collection class for this purpose?</p>
  
  <p><strong>Edit:</strong> I used <code>ConcurrentBag&lt;T&gt;</code> after spender's answer:</p>
  
  <pre><code>public sealed class Pool&lt;T&gt;
  {
      private readonly Func&lt;T&gt; initializer;
  
      private readonly ConcurrentBag&lt;T&gt; bag;
  
      public Pool(Func&lt;T&gt; initializer)
      {
          if (initializer == null)
              throw new ArgumentNullException("initializer");
  
          this.initializer = initializer;
          this.bag = new ConcurrentBag&lt;T&gt;();
      }
  
      public Pool(Func&lt;T&gt; initializer, IEnumerable&lt;T&gt; collection)
      {
          if (initializer == null)
              throw new ArgumentNullException("initializer");
  
          if (collection == null)
              throw new ArgumentNullException("initializer");
  
          this.initializer = initializer;
          this.bag = new ConcurrentBag&lt;T&gt;(collection);
      }
  
      public Pool(Func&lt;T&gt; initializer, int allocationCount)
          : this(initializer)
      {
          if (allocationCount &lt; 0)
              throw new ArgumentOutOfRangeException("allocationCount");
  
          for (int i = 0; i &lt; allocationCount; i++)
              this.bag.Add(initializer.Invoke());
      }
  
      public void Push(T item)
      {
          this.bag.Add(item);
      }
  
      public T Pop()
      {
          T item;
          return this.bag.TryTake(out item)
              ? item
              : this.initializer.Invoke();
      }
  }
  </code></pre>