> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Working With Event Hub NET SDK

> Guide to using Azure Event Hubs .NET SDK, showing producing, batching, and consuming events with sample code

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/4asMmWJpkl1BXMJG/images/AZ-204-Developing-Solutions-for-Microsoft-Azure/Exploring-Azure-Event-Hubs/Working-With-Event-Hub-NET-SDK/working-eventhub-dotnet-slide.jpg?fit=max&auto=format&n=4asMmWJpkl1BXMJG&q=85&s=b365c5493ccf06103ab565f76a781b30" alt="A presentation slide titled &#x22;Working with Event Hub .NET SDK.&#x22; It features a blue-green curved background on the right with an Event Hub-style icon and a small © Copyright KodeKloud note." width="1920" height="1080" data-path="images/AZ-204-Developing-Solutions-for-Microsoft-Azure/Exploring-Azure-Event-Hubs/Working-With-Event-Hub-NET-SDK/working-eventhub-dotnet-slide.jpg" />
</Frame>

This guide demonstrates common patterns for using the Azure Event Hubs .NET SDK: creating producer and consumer clients, inspecting partitions, publishing event batches, and reading events. It includes short focused examples and a complete Program.cs sample you can run locally.

Reference: [Azure Event Hubs .NET SDK overview](https://learn.microsoft.com/en-us/dotnet/api/overview/azure/messaging.eventhubs-readme) and [Azure Event Hubs documentation](https://learn.microsoft.com/azure/event-hubs/).

Quick summary (what you’ll learn)

* How to instantiate `EventHubProducerClient` and examine partition IDs.
* How to create an `EventDataBatch`, add events, and send them to an Event Hub.
* How to instantiate `EventHubConsumerClient` and read events with a cancellation token.

Overview of primary SDK types

| Resource / Type | Purpose | Typical usage example |
| - | -: | - |
| `EventHubProducerClient` | Send events to an Event Hub and inspect partitions | `new EventHubProducerClient(connectionString, eventHubName)` |
| `EventDataBatch` | Pack multiple `EventData` instances into a batch that fits service limits | `producer.CreateBatchAsync()` |
| `EventData` | Represents a single event payload | `new EventData(new BinaryData("payload"))` |
| `EventHubConsumerClient` | Receive events from a consumer group | `new EventHubConsumerClient(consumerGroup, connectionString, eventHubName)` |
| `PartitionEvent` | A received event plus partition/context metadata | `await foreach (PartitionEvent e in consumer.ReadEventsAsync(...))` |

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.

```csharp theme={null}
await using (var producer = new EventHubProducerClient(connectionString, eventHubName))
{
    string[] partitionIds = await producer.GetPartitionIdsAsync();
    // Partition IDs can be iterated or inspected to understand partition layout
}
```

Creating and sending a batch of events

Batching is efficient and ensures the client respects the service-side size constraints. Create an `EventDataBatch` with `CreateBatchAsync`, add events via `TryAdd`, and then send the batch using `SendAsync`.

```csharp theme={null}
await using (var producer = new EventHubProducerClient(connectionString, eventHubName))
{
    using EventDataBatch eventBatch = await producer.CreateBatchAsync();
    eventBatch.TryAdd(new EventData(new BinaryData("First")));
    eventBatch.TryAdd(new EventData(new BinaryData("Second")));

    await producer.SendAsync(eventBatch);
    // The batch is now sent to the Event Hub
}
```

Reading events from an Event Hub

Use an `EventHubConsumerClient` to read from a consumer group. `ReadEventsAsync` returns a stream of `PartitionEvent` instances. Use a `CancellationTokenSource` to limit how long the consumer listens.

```csharp theme={null}
string consumerGroup = EventHubConsumerClient.DefaultConsumerGroupName;

await using (var consumer = new EventHubConsumerClient(consumerGroup, connectionString, eventHubName))
{
    using var cancellationSource = new CancellationTokenSource();
    cancellationSource.CancelAfter(TimeSpan.FromSeconds(45));

    await foreach (PartitionEvent receivedEvent in consumer.ReadEventsAsync(cancellationSource.Token))
    {
        // Process each received event
        Console.WriteLine("Event Received: " + receivedEvent.Data.EventBody.ToString());
    }
}
```

A complete example

The consolidated Program.cs below demonstrates inspecting partitions, publishing a batch, and reading events. Replace `connectionString` with the connection string you copy from the [Azure portal](https://portal.azure.com) (either the Event Hubs namespace or hub-level SAS policy). Ensure the connection string you use has `send` and/or `listen` permissions as needed.

<Callout icon="lightbulb" color="#1CB2FE">
  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.
</Callout>

```csharp theme={null}
using System;
using System.Threading;
using System.Threading.Tasks;
using Azure.Messaging.EventHubs;
using Azure.Messaging.EventHubs.Producer;
using Azure.Messaging.EventHubs.Consumer;

class Program
{
    // Replace with your Event Hubs connection string and hub name
    private const string connectionString = "<EVENT_HUB_CONNECTION_STRING>";
    private const string eventHubName = "hub-01";
    private const string consumerGroup = EventHubConsumerClient.DefaultConsumerGroupName;

    static async Task Main(string[] args)
    {
        await InspectEventHub();
        await PublishEventsToEventHub();
        await ReadEventsFromEventHub();
    }

    static async Task InspectEventHub()
    {
        Console.WriteLine("Inspecting Event Hub...");

        await using (var producer = new EventHubProducerClient(connectionString, eventHubName))
        {
            string[] partitionIds = await producer.GetPartitionIdsAsync();
            Console.WriteLine($"Found {partitionIds.Length} partition(s): {string.Join(", ", partitionIds)}");
        }
    }

    static async Task PublishEventsToEventHub()
    {
        Console.WriteLine("Publishing events to Event Hub...");

        await using (var producer = new EventHubProducerClient(connectionString, eventHubName))
        {
            using EventDataBatch eventBatch = await producer.CreateBatchAsync();

            eventBatch.TryAdd(new EventData(new BinaryData("Hello, let's learn Azure Event Hubs!")));
            eventBatch.TryAdd(new EventData(new BinaryData("Let's learn to send events to Event Hubs!")));

            await producer.SendAsync(eventBatch);
            Console.WriteLine("Events sent.");
        }
    }

    static async Task ReadEventsFromEventHub()
    {
        Console.WriteLine("Reading events from Event Hub...");

        await using (var consumer = new EventHubConsumerClient(consumerGroup, connectionString, eventHubName))
        {
            using var cancellationSource = new CancellationTokenSource();
            cancellationSource.CancelAfter(TimeSpan.FromSeconds(45));

            await foreach (PartitionEvent receivedEvent in consumer.ReadEventsAsync(cancellationSource.Token))
            {
                Console.WriteLine("Event Received: " + receivedEvent.Data.EventBody.ToString());
            }
        }
    }
}
```

Running the example

* Build and run with `dotnet run`.
* The program will:
  1. List the Event Hub partition IDs.
  2. Publish the two example events as a single batch.
  3. Listen for incoming events for up to 45 seconds and print any that arrive.
* If other producers (for example, an [App Service](https://learn.microsoft.com/azure/app-service/) configured to send to this hub) are sending messages, this consumer will receive them while it is listening.

Best practices and tips

* Scope clients to the operation: create separate producer/consumer instances for distinct operations or lifetimes.
* Use `EventDataBatch` to 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.

Further reading and references

* [Azure Event Hubs .NET SDK overview](https://learn.microsoft.com/en-us/dotnet/api/overview/azure/messaging.eventhubs-readme)
* [Azure Event Hubs documentation](https://learn.microsoft.com/azure/event-hubs/)
* [Azure portal](https://portal.azure.com) — obtain connection strings and manage SAS policies

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/az-204-developing-solutions-for-microsoft-azure/module/a75906db-1eb1-43d3-a85d-1f45747df946/lesson/8c90d334-7f20-4a16-8c80-9c47be67db85" />

  <Card title="Practice Lab" icon="flask-conical" cta="Learn more" href="https://learn.kodekloud.com/user/courses/az-204-developing-solutions-for-microsoft-azure/module/a75906db-1eb1-43d3-a85d-1f45747df946/lesson/3d41b63d-8314-4d88-bb05-a2d7f7f47218" />
</CardGroup>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.