superlogical
superlogical

Reputation: 14950

Correct way to dispose a batch of Memory streams in C#

I have the following code but am worried about the creation of a List<MemoryStream> just so I can dispose them in the try..finally block

/// <summary>
/// Emit a batch of log events, running to completion asynchronously.
/// </summary>
/// <param name="events">The events to emit.</param>
/// <remarks>Override either <see cref="PeriodicBatchingSink.EmitBatch"/> or <see cref="PeriodicBatchingSink.EmitBatchAsync"/>,
/// not both.</remarks>
protected override async Task EmitBatchAsync(IEnumerable<LogEvent> events)
{
    var streams = new List<MemoryStream>();
    try
    {
        var req = new PutRecordsRequest { StreamName = streamName };

        foreach (var logEvent in events)
        {
            var json = await JsonConvert.SerializeObjectAsync(logEvent);
            var payload = Encoding.UTF8.GetBytes(json);
            var data = new MemoryStream(payload);

            var entry = new PutRecordsRequestEntry
            {
                PartitionKey = Guid.NewGuid().ToString(),
                Data = data
            };

            req.Records.Add(entry);
            streams.Add(data);
        }

        await client.PutRecordsAsync(req);
    }
    catch (Exception e)
    {
        SelfLog.WriteLine(e.ToString());
    }
    finally
    {
        streams.ForEach(x => x.Close());
    }
}

Upvotes: 2

Views: 634

Answers (1)

Henk Holterman
Henk Holterman

Reputation: 273179

When that streams is only used in the finally then you're better off without it.

A MemoryStream does not actually need to be Disposed (Closed) and when it's in some async pipeline, leave it be. The Garbage collector will reclaim it.

Upvotes: 1

Related Questions