I have a large database of messages I need to send to other systems. The messages average 5-10mb in size but some are larger (50-70mb). I need to base64 encode each message to disk. My application is consuming a large amount of memory encoding the messages to disk and I cannot figure out why.
What I have tried: I have read multiple posts regarding dispose method. I have implemented the dispose function as much as I can (via using) to release resources but I am still observing high memory usage (700mb+) for my Console application.
To keep things simple, I selected the 10 largest files from my database that range from 55-75mb. Under normal circumstances, the application will be processing messages 24/7.
Here is what my memory usage looks like when executing the below code. The flat line indicates the end of processing the large files. Why are these resources not being released?
Here is a capture of my heap view:
Here's my code:
const string sql = "SELECT TOP 10 * FROM [dbo].[OutboundMessages] ORDER BY [Length] DESC";
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(sql, connection))
using (SqlDataReader reader = command.ExecuteReader(CommandBehavior.SequentialAccess))
{
if (reader.HasRows)
{
while (reader.Read())
{
using (MemoryStream stream = new MemoryStream())
{
int ordinal = reader.GetOrdinal("FileData");
long bytesRead, offset = 0;
byte[] buffer = new byte[4096];
while ((bytesRead = reader.GetBytes(ordinal, offset, buffer, 0, buffer.Length)) > 0)
{
offset += bytesRead;
stream.Write(buffer, 0, (int)bytesRead);
}
string file = Guid.NewGuid().ToString().Replace("-", string.Empty);
using (StreamWriter writer = new StreamWriter(file))
{
writer.Write(Convert.ToBase64String(stream.ToArray()));
}
}
}
}
}
}

