123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- using System;
- using System.Collections.Generic;
- using System.Text;
- public class ObjectPool<T> where T : class
- {
- private readonly Stack<T> _objects = new Stack<T>();
- private readonly Func<T> _objectGenerator;
- public ObjectPool(Func<T> objectGenerator)
- {
- if (objectGenerator == null)
- {
- throw new ArgumentNullException("objectGenerator");
- }
- _objectGenerator = objectGenerator;
- }
- public T Get()
- {
- lock (_objects)
- {
- if (_objects.Count > 0)
- {
- return _objects.Pop();
- }
- }
- return _objectGenerator();
- }
- public void Put(T item)
- {
- lock (_objects)
- {
- _objects.Push(item);
- }
- }
- public override string ToString()
- {
- lock (_objects)
- {
- StringBuilder sb = new StringBuilder();
- foreach (T o in _objects)
- {
- sb.Append(o.ToString()).Append('\n');
- }
- return sb.ToString();
- }
- }
- public void Clear()
- {
- lock (_objects)
- {
- _objects.Clear();
- }
- }
- }
|