Skip to content

Instantly share code, notes, and snippets.

@brettsam
Created February 11, 2022 17:11
Show Gist options
  • Save brettsam/621da2d77343ee0290ea0ff81dc9c927 to your computer and use it in GitHub Desktop.
Save brettsam/621da2d77343ee0290ea0ff81dc9c927 to your computer and use it in GitHub Desktop.
EH Producer
using Azure.Messaging.EventHubs;
using Azure.Messaging.EventHubs.Producer;
using System.Text;
string connectionString = "<EH CONNSTRING>";
string eventHubName = "test";
int numOfEventsPerBatch = 10;
EventHubProducerClient producerClient = new EventHubProducerClient(connectionString, eventHubName);
async Task SendBatchAsync()
{
using (EventDataBatch eventBatch = await producerClient.CreateBatchAsync())
{
for (int i = 1; i <= numOfEventsPerBatch; i++)
{
if (!eventBatch.TryAdd(new EventData(Encoding.UTF8.GetBytes($"Event {i}"))))
{
// if it is too large for the batch
throw new Exception($"Event {i} is too large for the batch and cannot be sent.");
}
}
// Use the producer client to send the batch of events to the event hub
await producerClient.SendAsync(eventBatch);
Console.WriteLine($"A batch of {numOfEventsPerBatch} events has been published.");
}
}
try
{
for (int i = 0; i < 10; i++)
{
await SendBatchAsync();
}
}
finally
{
await producerClient.DisposeAsync();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment