我正在使用Channel
fromSystem.Threading.Channels
并希望批量读取项目(5 个项目),我有如下方法,
public class Batcher
{
private readonly Channel<MeasurementViewModel> _channel;
public Batcher()
{
_channel = Channel.CreateUnbounded<MeasurementViewModel>();
}
public async Task<MeasurementViewModel[]> ReadBatchAsync(int batchSize, CancellationToken stoppingToken)
{
var result = new MeasurementViewModel[batchSize];
for (var i = 0; i < batchSize; i++)
{
result[i] = await _channel.Reader.ReadAsync(stoppingToken);
}
return result;
}
}
在 asp.net 核心后台服务中,我正在使用它,如下所示,
public class WriterService : BackgroundService
{
private readonly Batcher _batcher;
public WriterService(Batcher batcher)
{
_batcher = batcher;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
var batchOfItems = await _batcher.ReadBatchAsync(5, stoppingToken);
var range = string.Join(',', batchOfItems.Select(item => item.Value));
var x = range;
}
}
}
这是有效的,只要有 5 个项目Channel
,我就会得到range
。
问题是,当只剩下 2 个项目Channel
并且自最后 10 分钟以来没有项目出现时Channel
,那么如何读取剩余的 2 个项目Channel
?