Does C# maintain queue for events?

292 Views Asked by At

I am working on an IoT application and using C# events to subscribe to MQTT messages. I am using a library that raises an event when a message is received. I have written an Asynchronous EventHandler for processing the message.

The rate at which the messages are being received is higher than the rate of processing them. In this case, I see a delay in the processing of messages, even though the EventHandler is asynchronous.

My question is does C# internally maintain some queue for EventHandlers? If, so can I access that queue for diagnostics purposes? By accessing that queue, I can analyze the exact load which causes the delay.

EDIT

Following is my setup,

  1. I have .NET Framework 4.6.2 console application.
  2. In the application I use MQTTnet library for subscribing to MQTT messages.
  3. Following is the code I use for subscribing,
var mqttFactory = new MqttFactory();

var client = mqttFactory.CreateMqttClient();

client.ApplicationMessageReceivedAsync += async e =>
{
    // Process the message. Ex: Update database
}

var clientOptions = mqttFactory.CreateClientOptionsBuilder()
    .WithTcpServer("mqtt-broker-host", 9000)
    .Build();

await client.ConnectAsync(clientOptions);
await client.SubscribeAsync("mqtt-topic");
  1. In the handler I process the message. The main part of processing is updating the records in the database.
2

There are 2 best solutions below

6
Marc Gravell On

EventHandler is intended to be synchronous; there is no queue of any kind. If you want some kind of queuing mechanism, maybe consider Channel<T>, which is an async queue-like device intended for independent write ("pub") and read ("sub"); or if your requirements are more complex, a range of in-process and out-of-process message-queue / event broker tools are available.

0
JonasH On

My question is does C# internally maintain some queue for EventHandlers?

No, an event handler is essentially just a list of delegates. And raising an event just loops over all the delegates and calls them in turn.

Adding async to a method does not automatically make anything asynchronously. It just allow you to await asynchronous methods, but sometimes methods lie about being asynchronous.

There are some queues in C#, like the message queue for the UI thread, but I do not think this is relevant in this particular.

If, so can I access that queue for diagnostics purposes. By accessing that queue, I can analyze the exact load which causes the delay.

This sounds like you want to use a performance profiler. This should tell you how much CPU time is spent in each portion of the code, and if some code is blocking for some reason. The best solution would be if you could solve your performance problem by optimization or avoid doing anything "slow".