在C#中配置一批内存流的正确方法

时间:2015-04-19 20:42:33

标签: c#

我有以下代码,但我担心创建一个List<MemoryStream>,所以我可以将它们放在try..finally块中

/// <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());
    }
}

1 个答案:

答案 0 :(得分:1)

streams仅用于终结时,如果没有它,你会更好。

MemoryStream实际上不需要处置(关闭),当它在某个异步管道中时,请保留它。垃圾收集器将收回它。