How about long running work that is done using an async method
Author: alizahid4004Created Sep 22, 2021Updated Feb 15, 2025
For something like the following:
What is the best approach of executing the long running work in the background? I have looked everywhere and I've found a lot of contradicting advice on this.
public class QueueProcessor
{
private readonly BlockingCollection _messageQueue = new BlockingCollection();
public void StartProcessing()
{
//Start background processing here. What's the best approach?
}
public void Enqueue(Message message)
{
_messageQueue.Add(message);
}
private async Task ProcessQueue() //notice the async Task here
{
foreach (var item in _messageQueue.GetConsumingEnumerable())
{
await ProcessItem(item).ConfigureAwait(false);
}
}
private async Task ProcessItem(Message message) { }
}
Source: davidfowl/AspNetCoreDiagnosticScenarios