Why does a memorystream work and a RecyclableMemoryStream not?
Sicos1977 opened this issue · 2 comments
Sicos1977 commented
When running the code like this it will return an array that is filled
public static byte[] DataContractSerializerToDeflatedByteArray(string xml)
{
using (var memoryStream = new MemoryStream())
{
using (var deflateStream = new DeflateStream(memoryStream, CompressionMode.Compress))
{
var bytes = Encoding.UTF8.GetBytes(xml);
deflateStream.Write(bytes, 0, bytes.Length);
}
return memoryStream.ToArray();
}
}
When running it as this the array always has a length of 0
public static byte[] DataContractSerializerToDeflatedByteArray(string xml)
{
using (var memoryStream = StreamHelpers.Manager.GetStream("Serialization.DataContractSerializerToDeflatedByteArray"))
{
using (var deflateStream = new DeflateStream(memoryStream, CompressionMode.Compress))
{
var bytes = Encoding.UTF8.GetBytes(xml);
deflateStream.Write(bytes, 0, bytes.Length);
deflateStream.Flush();
return memoryStream.ToArray();
}
}
}
And running it like this it always gives a already disposed exception
public static byte[] DataContractSerializerToDeflatedByteArray(string xml)
{
using (var memoryStream = StreamHelpers.Manager.GetStream("Serialization.DataContractSerializerToDeflatedByteArray"))
{
using (var deflateStream = new DeflateStream(memoryStream, CompressionMode.Compress))
{
var bytes = Encoding.UTF8.GetBytes(xml);
deflateStream.Write(bytes, 0, bytes.Length);
deflateStream.Flush();
}
return memoryStream.ToArray();
}
}
Sicos1977 commented
The StreamHelpers class
public static class StreamHelpers
{
#region Consts
private const int BlockSize = 1024;
private const int LargeBufferMultiple = 1024 * 1024;
private const int MaxBufferSize = 16 * LargeBufferMultiple;
#endregion
#region Fields
private static RecyclableMemoryStreamManager _manager;
#endregion
#region Properties
/// <summary>
/// https://github.com/microsoft/Microsoft.IO.RecyclableMemoryStream
/// </summary>
public static RecyclableMemoryStreamManager Manager
{
get
{
if (_manager != null)
return _manager;
_manager = new RecyclableMemoryStreamManager(BlockSize, LargeBufferMultiple, MaxBufferSize)
{
//_manager.GenerateCallStacks = true;
AggressiveBufferReturn = false,
MaximumFreeLargePoolBytes = MaxBufferSize * 4,
MaximumFreeSmallPoolBytes = 100 * BlockSize
};
return _manager;
}
}
#endregion
}
Sicos1977 commented
Never mind it is fixed, seems that I have to leave the memorystream open like this
public static byte[] DataContractSerializerToDeflatedByteArray(string xml)
{
using (var memoryStream = StreamHelpers.Manager.GetStream("Serialization.DataContractSerializerToDeflatedByteArray"))
{
using (var deflateStream = new DeflateStream(memoryStream, CompressionMode.Compress, true))
{
var bytes = Encoding.UTF8.GetBytes(xml);
deflateStream.Write(bytes, 0, bytes.Length);
}
return memoryStream.ToArray();
}
}