gpt4 book ai didi

c# - 在 C# 中处理一批内存流的正确方法

转载 作者:太空宇宙 更新时间:2023-11-03 13:09:14 27 4
gpt4 key购买 nike

我有以下代码,但担心创建 List<MemoryStream>这样我就可以在 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());
}
}

最佳答案

streams 仅在 finally 中使用时,最好不要使用它。

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

关于c# - 在 C# 中处理一批内存流的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29735606/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com