CodexBloom - Programming Q&A Platform

C# 11 MQTT Client Connection Timeout Not Triggering as Expected in .NET 7 Application

πŸ‘€ Views: 27 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-12
c# .net mqtt async timeout csharp

I'm converting an old project and Can someone help me understand Quick question that's been bugging me - Quick question that's been bugging me - I'm working on a .NET 7 application using the MQTTnet library to connect to an MQTT broker... I've implemented the connection logic, but I'm working with an scenario where the connection timeout does not seem to trigger as expected. I’ve set a timeout of 5 seconds, but when the broker is unreachable, my application hangs indefinitely instead of timing out. Here’s the snippet of my connection code: ```csharp var factory = new MqttFactory(); var mqttClient = factory.CreateMqttClient(); var options = new MqttClientOptionsBuilder() .WithClientId("test_client") .WithTcpServer("broker.hivemq.com", 1883) .WithCleanSession() .Build(); var cancellationTokenSource = new CancellationTokenSource(); try { var connectTask = mqttClient.ConnectAsync(options, cancellationTokenSource.Token); connectTask.Wait(5000); // Set timeout to 5 seconds } catch (AggregateException ex) { if (ex.InnerExceptions.Any(e => e is TaskCanceledException)) { Console.WriteLine("Connection timed out"); } else { Console.WriteLine(ex.Message); } } ``` I expect that the task waits for a maximum of 5 seconds, after which it either connects or throws a timeout exception. However, when the broker is down, the application hangs without throwing the expected exception. I tried to verify if the scenario was with task cancellation by checking the status of the task, but it remains in a running state even after 5 seconds. I've also checked the MQTTnet documentation, but I couldn't find any specific implementation that deals with this scenario. Has anyone experienced a similar question, or does anyone know how to properly implement a timeout for the MQTT connection in C#? I'm using MQTTnet version 4.0.0. Thanks for your help! I'm working on a application that needs to handle this. Thanks in advance! For context: I'm using Csharp on Ubuntu. Thanks for your help in advance! What are your experiences with this?