Jason Goemaat
Jason Goemaat

Reputation: 122

Is there a way to easily receive messages currently in C# from a ServiceBus subscription?

Looking at the documentation, there doesn't appear to be a way to simply read some messages and handle them anymore.

My problem is I want a program or task to check a queue and handle some messages, and I don't want this program or task to exist any longer than to empty the subscription of messages.

Here is the sample code for example:

// Register subscription message handler and receive messages in a loop
RegisterOnMessageHandlerAndReceiveMessages();
Console.ReadKey();
await subscriptionClient.CloseAsync();

What I want to do is replace Console.ReadKey(); with something that will continue on when the queue is empty. The way the classes are setup though is that you have to set an error handler and a message handler, then it will basically call your handlers when events occur until you tell it to stop. I don't see any kind of message that will let you know when there are no messages left though.

Upvotes: 1

Views: 1162

Answers (2)

Jason Goemaat
Jason Goemaat

Reputation: 122

There is a class called MessageReceiver I found in the examples repo which offers the functionality I need.

string subscriptionEntityPath = "my-topic/subscriptions/my-subscription";
MessageReceiver receiver = new MessageReceiver(
    serviceBusConnectionString,
    subscriptionEntityPath,
    ReceiveMode.PeekLock);
var message = await receiver.ReceiveAsync(TimeSpan.FromSeconds(5));
while (message != null)
{
    // handle message

    message = await receiver.ReceiveAsync(TimeSpan.FromSeconds(5));
}
await receiver.CloseAsync();

Upvotes: 0

Sean Feldman
Sean Feldman

Reputation: 26057

My problem is I want a program or task to check a queue and handle some messages, and I don't want this program or task to exist any longer than to empty the subscription of messages.

The message handler construct is not designed for the scenario you're describing. It's intended for a continuous flow of messages. In your case, messages are not available all the time and you want to respond to those when they are available. There are two ways to handle it with a reactive approach.

  1. Azure Functions. With Azure Functions there's still a polling mechanism that runs 24/7 but you don't own it and don't need to run it. From your function's perspective, the code is invoked whenever there are messages.
  2. Event Grid triggered processing. You can use Event Grid to trigger an event when messages are available for processing and no consumer is connected. That way you can trigger processing using any option and not just Azure Functions. Once messages are processed the process can exit until there are more messages and Event Grid emit a notification event again. Note that this option is only available with Azure Service Bus premium.

Upvotes: 1

Related Questions