DEV Community

Kenichiro Nakamura
Kenichiro Nakamura

Posted on

C# SDK for Event Hub: Read stream from the latest message

The official documentation explains Azure Event Hub as:

Azure Event Hubs is a big data streaming platform and event ingestion service. It can receive and process millions of events per second

There is C# (and many other) SDK to use the service. I am using dotnet core SDK

Issue

I need to get messages since I subscribed to the event hub, but by default, event hub retains data for 1 day and the sample code gets all the old messages. I can use checkpoint to remember where I last read the message for next time, but I always want to get data from the point I open connection.

Resolution

Sample application shows how to subscribe events.

// Register handlers for processing events and handling errors
processor.ProcessEventAsync += ProcessEventHandler;
processor.ProcessErrorAsync += ProcessErrorHandler;

In addition to above, I just needed to subscribe PartitionInitializingAsync event.

processor.PartitionInitializingAsync+= ProcessInitializingHandler;

static async Task ProcessInitializingHandler(PartitionInitializingEventArgs eventArgs)
{
    eventArgs.DefaultStartingPosition = EventPosition.Latest;
}

That's it! You can also set FromOffset, FromEnqueuedTime for more granular control.

Reference

You can find official sample in GitHub

Top comments (0)