0

I am using Azure service bus for messaging between my two .Net core Web API Applications. By using topicClient I am able to send the message to ABS. But however while using the subscription client to receive the message, I am facing this issue.

ProcessMessagesAsync - method is not firing until I give "Console.Read();". I cannot give this because I am using Web API.

How else, can I fire this ProcessMessagesAsync method - which read my message perfectly.

Thanks in advance.

    public async Task GetMessageFromSubscription()
        {

        subscriptionClient = new SubscriptionClient(ServiceBusConnectionString, TopicName, SubscriptionName);

                RegisterOnMessageHandlerAndReceiveMessages();
                //  Console.Read();  ------- Without this line 

                await subscriptionClient.CloseAsync();
           }

 public void RegisterOnMessageHandlerAndReceiveMessages()
        {
            var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler);
            subscriptionClient.RegisterMessageHandler(ProcessMessagesAsync, messageHandlerOptions);
         }


        private async Task ProcessMessagesAsync(Message message, CancellationToken token)
        {
               var messageBody = Encoding.UTF8.GetString(message.Body);
                var serviceBusMessage = JsonConvert.DeserializeObject<WorkIntakeItem>(messageBody);
                await subscriptionClient.CompleteAsync(message.SystemProperties.LockToken);

         }

user2294434
  • 123
  • 4
  • 16

1 Answers1

1

It's a loop that is running as along as the process is running. When process ends, the handler will be terminated.

If you have a continues stream of messages, handler (aka message pump) is a suitable option. If you just need to receive one message and exit, then there's an blocking option of Message MessageReceiver.ReceiveAsync. You control the app to you when to close it.

static IMessageReceiver messageReceiver;
RegisterOnMessageHandlerAndReceiveMessages();
Message message = await messageReceiver.ReceiveAsync();
await messageReceiver.CompleteAsync(message.SystemProperties.LockToken);
await messageReceiver.CloseAsync();
await subscriptionClient.CloseAsync();

For more details, you could refer to this article.

Joey Cai
  • 18,968
  • 1
  • 20
  • 30