30 lines
791 B
C#
30 lines
791 B
C#
// 简易对象池
|
|
using System.Collections.Concurrent;
|
|
using System.IO;
|
|
public class SimpleMemoryStreamPool
|
|
{
|
|
private static readonly ConcurrentBag<MemoryStream> _pool = new ConcurrentBag<MemoryStream>();
|
|
private const int MaxPoolSize = 50;
|
|
|
|
public static MemoryStream Rent(int capacity = 1024)
|
|
{
|
|
MemoryStream stream;
|
|
if (_pool.TryTake(out stream))
|
|
{
|
|
stream.SetLength(0);
|
|
stream.Position = 0;
|
|
return stream;
|
|
}
|
|
return new MemoryStream(capacity);
|
|
}
|
|
|
|
public static void Return(MemoryStream stream)
|
|
{
|
|
if (stream != null && _pool.Count < MaxPoolSize)
|
|
{
|
|
stream.SetLength(0);
|
|
stream.Position = 0;
|
|
_pool.Add(stream);
|
|
}
|
|
}
|
|
} |