
- How to instantiate
EventHubProducerClientand examine partition IDs. - How to create an
EventDataBatch, add events, and send them to an Event Hub. - How to instantiate
EventHubConsumerClientand read events with a cancellation token.
Instantiating an Event Hub (inspect partitions)
To connect and inspect partition information, create an
EventHubProducerClient. Retrieving partition IDs with GetPartitionIdsAsync() helps you understand how messages will be distributed across partitions.
EventDataBatch with CreateBatchAsync, add events via TryAdd, and then send the batch using SendAsync.
EventHubConsumerClient to read from a consumer group. ReadEventsAsync returns a stream of PartitionEvent instances. Use a CancellationTokenSource to limit how long the consumer listens.
connectionString with the connection string you copy from the Azure portal (either the Event Hubs namespace or hub-level SAS policy). Ensure the connection string you use has send and/or listen permissions as needed.
Make sure the connection string has the appropriate permissions (send and/or listen). Create a SAS policy at the Event Hub level or use the namespace-level
RootManageSharedAccessKey if you need all permissions.- Build and run with
dotnet run. - The program will:
- List the Event Hub partition IDs.
- Publish the two example events as a single batch.
- Listen for incoming events for up to 45 seconds and print any that arrive.
- If other producers (for example, an App Service configured to send to this hub) are sending messages, this consumer will receive them while it is listening.
- Scope clients to the operation: create separate producer/consumer instances for distinct operations or lifetimes.
- Use
EventDataBatchto avoid exceeding service-side size limits when sending multiple events. - Always use a cancellation token when reading so the consumer doesn’t block indefinitely.
- For production, consider using retry policies and proper error handling for transient failures.
- Azure Event Hubs .NET SDK overview
- Azure Event Hubs documentation
- Azure portal — obtain connection strings and manage SAS policies