azureazure-eventhubazure-eventgridazure-eventhub-client

ReadEventsAsync EventHub Wont Stop


I am storing some application-generated messages in Azure Event Hub, which is being produced by a web app, I would like to retrieve these messages from Azure Event Hub in a Rest API call to show these in a web app.

Issue

When I try reading messages from Azure Event Hub using the following code

var messages = new List<MessagingModel>();

            string consumerGroup = EventHubConsumerClient.DefaultConsumerGroupName;

            await using (var consumerClient = new EventHubConsumerClient(consumerGroup, eventHubConnectionString, eventHubName))
            {
                await foreach (var partitionEvent in consumerClient.ReadEventsAsync())
                {
                    string json = Encoding.UTF8.GetString(partitionEvent.Data.Body.ToArray());
                    var message = JsonConvert.DeserializeObject<MessagingModel>(json);
                    Console.WriteLine(json);
                }

                await consumerClient.CloseAsync();
            }

            return messages;

control never comes out of for each, that is not what is desired, also I have observed when a new message is sent to Event Hub, the control comes back to process that message and then waits for the next message to come up.

I would like to just read the list of messages.


Solution

  • You can break the loop when there are no more events to receive. Check the sample below.

    https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/eventhub/Azure.Messaging.EventHubs/samples/Sample05_ReadingEvents.md#read-events-from-all-partitions-with-a-maximum-wait-time