I have Windows Service written in C#, which is subscribing to Event hubs and listening to them for any messages.
The code I have followed is as follows:
public class SimpleEventProcessor : IEventProcessor
{
public Task CloseAsync(PartitionContext context, CloseReason reason)
{
Console.WriteLine($"Processor Shutting Down. Partition '{context.PartitionId}', Reason: '{reason}'.");
return Task.CompletedTask;
}
public Task OpenAsync(PartitionContext context)
{
Console.WriteLine($"SimpleEventProcessor initialized. Partition: '{context.PartitionId}'");
return Task.CompletedTask;
}
public Task ProcessErrorAsync(PartitionContext context, Exception error)
{
Console.WriteLine($"Error on Partition: {context.PartitionId}, Error: {error.Message}");
return Task.CompletedTask;
}
public Task ProcessEventsAsync(PartitionContext context, IEnumerable<EventData> messages)
{
foreach (var eventData in messages)
{
var data = Encoding.UTF8.GetString(eventData.Body.Array, eventData.Body.Offset, eventData.Body.Count);
Console.WriteLine($"Message received. Partition: '{context.PartitionId}', Data: '{data}'");
DoSomethingWithMessage(); // typically takes 20-20 mins to finish this method.
}
return context.CheckpointAsync();
}
}
This is the sample code mentioned in this document.
Now I have 8 partitions on my event hub. So 8 partitions keep receiving messages as and when there is a new message. Whenever a message is received, a method is called DoSomethingWithMessage()
which takes around 30 mins to finish as it does some calculations.
I want my code to run synchronously, meaning when one message is received, service should first complete this method execution, then receive the next message. Now what is happening is , even when the DoSomethingWithMessage()
is still under execution, new messages are being received and that message is processed parallel to the first message, which is creating some calculation problems.
Is there a way I can receive messages one by one?