Files
Web_CRICS_Server_VS2010_Prod/Common/MemoryStreamPool.cs
2025-12-11 09:17:16 +08:00

43 lines
1.2 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Concurrent;
using System.IO;
namespace Common
{
/// <summary>
/// MemoryStream对象池用于高并发场景减少GC压力
/// </summary>
internal static class MemoryStreamPool
{
private static readonly ConcurrentBag<MemoryStream> pool = new ConcurrentBag<MemoryStream>();
private const int MaxPoolSize = 100;
private const int MaxStreamCapacity = 10240; // 10KB超过此大小的流不放回池中
public static MemoryStream Rent()
{
MemoryStream stream = null;
if (pool.TryTake(out stream))
{
stream.Position = 0;
stream.SetLength(0);
return stream;
}
return new MemoryStream();
}
public static void Return(MemoryStream stream)
{
if (stream != null && stream.Capacity <= MaxStreamCapacity && pool.Count < MaxPoolSize)
{
stream.Position = 0;
stream.SetLength(0);
pool.Add(stream);
}
}
}
}