I'd like to use Azure Service Bus on .Net Core and read only one message. It seems that Microsoft.Azure.ServiceBus
does not support such a case. So far testing code a bit got me this far:
public void ReceiveOne()
{
var queueClient = new QueueClient(ServiceBusConnectionString, "go_testing");
queueClient.RegisterMessageHandler(
async (message, token) =>
{
var messageBody = Encoding.UTF8.GetString(message.Body);
Console.WriteLine($"Received: {messageBody}, time: {DateTime.Now}");
await queueClient.CompleteAsync(message.SystemProperties.LockToken);
await queueClient.CloseAsync();
},
new MessageHandlerOptions(async args => Console.WriteLine(args.Exception))
{ MaxConcurrentCalls = 1, AutoComplete = false });
}
So I'm closing queue after successfully reading one message. It works, but it also triggers an exception.
Do you know a better way to achieve it?
I found a solution:
IMessageReceiver messageReceiver = new MessageReceiver(ServiceBusConnectionString, QueueName, ReceiveMode.PeekLock);
// Receive the message
Message message = await messageReceiver.ReceiveAsync();
// Process the message
Console.WriteLine($"Received message: SequenceNumber:{message.SystemProperties.SequenceNumber} Body:{Encoding.UTF8.GetString(message.Body)}");
// Complete the message so that it is not received again.
// This can be done only if the MessageReceiver is created in ReceiveMode.PeekLock mode (which is default).
await messageReceiver.CompleteAsync(message.SystemProperties.LockToken);
await messageReceiver.CloseAsync();
You will need to include:
using Microsoft.Azure.ServiceBus;
using Microsoft.Azure.ServiceBus.Core;
This is the original source: https://github.com/Azure/azure-service-bus/tree/master/samples/DotNet/GettingStarted/Microsoft.Azure.ServiceBus/SendReceiveUsingMessageSenderReceiver
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With