I have a BackgroundService/IHostedService in an ASP.NET API core app with a Channel, that awaits for something else to write on the channel, so it can read it and process it. The interval of which the items are written to the channel, could be every few seconds or minutes.
This service is long lived (same lifespan as the API app), and therefore the channel as well.
// Simplified/Example code
using System.Threading.Channels;
// ...
Channel<object> channel = Channel.CreateUnbounded<object>();
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (await channel.Reader.WaitToReadAsync(stoppingToken))
{
while (channel.Reader.TryRead(out string item))
{
// Process item
}
}
}
My questions are:
- Is it recommendable to await
channel.Reader.WaitToReadAsync()for long periods? (could be several minutes before an item is written to the channel) - Is
channel.Reader.WaitToReadAsync()I/O bound? (Does it free up the thread when usingawait?) - Is it better to have an
AutoResetEventand block the thread instead of usingawait/async? (No wasted CPU cycles as the thread will simply go to sleep)
My primary concern is that channel.Reader.WaitToReadAsync() is CPU bound and awaiting for it, for long periods of times, wastes CPU resources, and should be better off using other methods like AutoResetEvent