'uPLibrary.Networking.M2Mqtt.MqttClient throwing CommunicationException and OutOfMemoryException

I am using uPLibrary.Networking.M2Mqtt to connect to MQTT broker.

var telemetryClient = new uPLibrary.Networking.M2Mqtt.MqttClient(
    mqttBaseAddress, MqttSettings.MQTT_BROKER_DEFAULT_SSL_PORT, true,
    new X509Certificate2($"certs/{rootCert}"), new X509Certificate2($"certs/{cert}", $"{certPw}"),
    MqttSslProtocols.TLSv1_2
    );

if (!telemetryClient.IsConnected)
{
     try
     { // Following line is getting exceptions
         telemetryClient.Connect(clientId, null, null, true, 10);

         telemetryClient.ConnectionClosed += (sender, args) =>
         {
             IoTCoreTelemetryStreamHealth.PublishEvent(IoTCoreTelemetryStreamHealth.Event.Disconnected);
         };

         telemetryClient.Subscribe(new[] { topic }, new[] { MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE });

         IoTCoreTelemetryStreamHealth.PublishEvent(IoTCoreTelemetryStreamHealth.Event.Connected);
     }
     catch (Exception exception)
     {
          CloseTelemetryStream(telemetryClient, true, topic);
          Task.Delay(DelayBeforeReconnect).ContinueWith(t => ConnectAndSubscribeForTelemetryTopic(serialNumber, src, clientId, telemetryClient, telemetryStreamType, topic));
     }
}

This has been working for a long time, without any serious issues.

After a while (months), I started getting two exceptions constantly, one after the other a lot of times from this line:

telemetryClient.Connect(clientId, null, null, true, 10);

The exceptions are:

uPLibrary.Networking.M2Mqtt.Exceptions.MqttCommunicationException: 
Exception of type 'uPLibrary.Networking.M2Mqtt.Exceptions.MqttCommunicationException' was thrown.    at
uPLibrary.Networking.M2Mqtt.MqttClient.SendReceive(Byte[] msgBytes, Int32 timeout)    at 
uPLibrary.Networking.M2Mqtt.MqttClient.Connect(String clientId, String username, String password, Boolean willRetain, Byte willQosLevel, Boolean willFlag, String willTopic, String willMessage, Boolean cleanSession, UInt16 keepAlivePeriod)

and

System.OutOfMemoryException: 
Exception of type 'System.OutOfMemoryException' was thrown.    at 
System.Threading.Thread.StartInternal()    at 
uPLibrary.Networking.M2Mqtt.MqttClient.Connect(String clientId, String username, String password, Boolean willRetain, Byte willQosLevel, Boolean willFlag, String willTopic, String willMessage, Boolean cleanSession, UInt16 keepAlivePeriod)    at 
DevicePortal.Telemetry.Service.Services.IotCoreServiceBase.ConnectAndSubscribeForTelemetryTopic(String serialNumber, String src, String clientId, MqttClient telemetryClient, String telemetryStreamType, String topic) in /src/DevicePortal.Telemetry.Service/Services/IotCoreServiceBase.cs:line 179


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source