c# bufferblock vs blockingcollection code example
Example: bufferblock vs blockingcollection
public class MyBackgroundService
{
private readonly BufferBlock<int> _queue = new BufferBlock<int>();
public void AddItem(int item)
{
_queue.Post(item);
}
public void Start()
{
Task.Run(async () =>
{
while (await _queue.OutputAvailableAsync())
{
var item = await _queue.ReceiveAsync();
await ProcessItem(item);
}
});
}
public Task Stop()
{
_queue.Complete();
return _queue.Completion;
}
private Task ProcessItem(int item)
{
return Task.Delay(item);
}
}