0

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.

Praveen Rao Chavan.G
  • 2,772
  • 3
  • 22
  • 33
  • It is important to note that the `ReadEventsAsync` method is NOT intended for use in production consuming scenarios- as its documentation calls out. That method exists to help with exploring Event Hubs and is suitable for one-off tools and similar where fairness and throughput are not concerns. – Jesse Squire Apr 29 '23 at 15:10

1 Answers1

2

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

Serkant Karaca
  • 1,896
  • 9
  • 8