Skip to content

Commit f5fad96

Browse files
committed
Fix IPoolObject should only return back to it's owning pool
1 parent 1a9400b commit f5fad96

File tree

3 files changed

+16
-11
lines changed

3 files changed

+16
-11
lines changed

src/Pooling/ArrayPool.cs

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -70,8 +70,6 @@ public void Free(object item)
7070
return;
7171
}
7272

73-
IPoolSource<T> elementSource = _arePooledItems ? PoolFactory.GetSource<T>() : null;
74-
7573
for (int i = 0; i < items.Length; i++)
7674
{
7775
object itm = items[i];
@@ -85,10 +83,6 @@ public void Free(object item)
8583
{
8684
obj.Source.Free(obj);
8785
}
88-
else if (elementSource != null)
89-
{
90-
elementSource.Free(obj);
91-
}
9286
}
9387
}
9488

src/Pooling/IPoolObject.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ public interface IPoolObject : IDisposable
77
/// <summary>
88
/// The source pool this item came from
99
/// </summary>
10-
IPoolSource Source { get; }
10+
IPoolSource Source { get; set; }
1111

1212
/// <summary>
1313
/// Instruct the <see cref="IPoolSource"/> to ignore this object

src/Pooling/ObjectPool.cs

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,26 +9,37 @@ internal class ObjectPool<T> : IPoolSource<T> where T : class
99

1010
private readonly Type _poolType;
1111
private readonly List<T> _pool;
12+
private readonly bool _isPooledInterface;
1213

1314
public ObjectPool()
1415
{
1516
_poolType = typeof(T);
1617
_pool = new List<T>();
18+
_isPooledInterface = typeof(IPoolObject).IsAssignableFrom(typeof(T));
1719
}
1820

1921
public T Get()
2022
{
23+
T item;
2124
lock (_pool)
2225
{
2326
if (_pool.Count == 0)
2427
{
25-
return (T)Activator.CreateInstance(typeof(T));
28+
item = (T)Activator.CreateInstance(typeof(T));
2629
}
30+
else
31+
{
32+
item = _pool[0];
33+
_pool.RemoveAt(0);
34+
}
35+
}
2736

28-
T item = _pool[0];
29-
_pool.RemoveAt(0);
30-
return item;
37+
if (_isPooledInterface && item is IPoolObject pooled)
38+
{
39+
pooled.Source = this;
3140
}
41+
42+
return item;
3243
}
3344

3445
public void Free(object item)

0 commit comments

Comments
 (0)