I'm attempting to implement a background service in DotNet that sends messages to a queue in Azure Service Bus. My code looks like this:
public class AuditBackgroundService : BackgroundService, IAuditBackgroundService
{
private readonly TimeSpan _sendInterval;
private readonly ServiceBusSender _sender;
private readonly ConcurrentQueue<string> _messageQueue = new ConcurrentQueue<string>();
public AuditBackgroundService(ServiceBusSender sender, IOptions<AuditConfiguration> config)
{
_sendInterval = TimeSpan.FromMilliseconds(config.Value.SendIntervalMilliseconds);
_sender = sender;
}
public void AddMessage(string message)
{
_messageQueue.Enqueue(message);
}
protected async override Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
await Task.Delay(_sendInterval, stoppingToken);
await ProcessMessagesAsync(stoppingToken);
}
}
private async Task ProcessMessagesAsync(CancellationToken cancellationToken)
{
if (!_messageQueue.IsEmpty)
{
while (_messageQueue.TryDequeue(out string message))
{
var busMessage = new ServiceBusMessage(message);
await _sender.SendMessageAsync(busMessage, cancellationToken);
}
}
}
}
As far as I can tell this is working just fine, and indeed from the overview page in Azure I can see I'm getting several successful requests, however no messages are actually hitting the queue.
I've utilized Microsoft's quickstart guide for instructions on how to set up a namespace and a queue for the Azure Service Bus, but despite following the instructions to a t I still can't seem to get it to work. Any idea what I may be doing wrong? Appreciate the help in advance.
