how to read remaining items in `Channel` less than batch size if there is no new items coming to `Channel` within X minutes

@IamCoder 391 Reputation points
2020-09-14T10:07:45.58+00:00

I am using Channel from System.Threading.Channels and wants to read items in batch (5 items) and I have a method like below,

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;
    }
}

and in asp.net core background service I am using it like below,

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;
        }
    }
}

and this is working and whenever there is 5 items in Channel, I am getting range.

Question is, when there are only 2 items left in Channel and since last 10 minutes NO items coming to Channel, then how to read the remaining 2 items in Channel?

Not Monitored
Not Monitored
Tag not monitored by Microsoft.
23,791 questions
No comments
{count} votes