question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

MQTTnet.Exceptions.MqttCommunicationException: Cannot access a disposed object

See original GitHub issue

Hello,

I have a task with a parallel.ForEach ( I have also tried with a simple foreach)

Parallel.ForEach(receiveMessageResponse.Messages, message =>
{
    if (!string.IsNullOrEmpty(message.Body))
    {
        try
        {
            mqtt.ManageMQTTClient(MQTTconfigPublisher, message.Body).GetAwaiter().GetResult();
        }
        catch (Exception e)
        {
            parallelExceptions.Enqueue(e);
        }
    }
});

And when I run the app I have the following error:

MQTTnet.Exceptions.MqttCommunicationException: Cannot access a disposed object
Object name: 'System.Net.Sockets.Socket'. ---> System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'System.Net.Sockets.Socket'.
at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
at System.Net.Sockets.Socket.<>c.<ConnectAsync>b__274_0(IAsyncResult iar)
--- End of stack trace from previous location where exception was thrown ---
at MQTTnet.Implementations.MqttTcpChannel.ConnectAsync(CancellationToken cancellationToken)
at MQTTnet.Internal.MqttTaskTimeout.WaitAsync(Func`2 action, TimeSpan timeout, CancellationToken cancellationToken)
at MQTTnet.Adapter.MqttChannelAdapter.ConnectAsync(TimeSpan timeout, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at MQTTnet.Adapter.MqttChannelAdapter.WrapException(Exception exception)
at MQTTnet.Adapter.MqttChannelAdapter.ConnectAsync(TimeSpan timeout, CancellationToken cancellationToken)
at MQTTnet.Client.MqttClient.ConnectAsync(IMqttClientOptions options, CancellationToken cancellationToken)
at MQTTnet.Client.MqttClient.ConnectAsync(IMqttClientOptions options, CancellationToken cancellationToken)
at AmpliaControlSystem.MQTT.ManageMQTTClient(MQTTConfiguration MQTTconfigPublisher, String payload) in /app/MQTT.cs:line 38

As a note, this happened to me in local, but I re-write the code from the beggining and it was fixed. Now I’m trying to deploy to AWS and the error happen again

The task ManageMQTTClient which produce the error:

public async Task ManageMQTTClient( MQTTConfiguration MQTTconfigPublisher, string payload)
{
    string topic = payload.Split(";")[1];
    string cliente =  Guid.NewGuid().ToString();
    try
    {
        IMqttClientOptions optionsPublisher = new MqttClientOptionsBuilder()
                    .WithTcpServer(MQTTconfigPublisher.Servidor)
                    .WithClientId(cliente)
                    .WithCredentials(MQTTconfigPublisher.Username, MQTTconfigPublisher.Password)
                    .WithCleanSession(false)
                    .WithKeepAlivePeriod(System.TimeSpan.FromSeconds(60))
                    .Build();

        IMqttClient mqttClientPublisher = new MqttFactory().CreateMqttClient();


        await mqttClientPublisher.ConnectAsync(optionsPublisher);
     
        if (mqttClientPublisher.IsConnected)
        {
            try
            {
                await mqttClientPublisher.PublishAsync(topic, payload.Split(";")[2], MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error en 1" + ex);
                throw;
            }
        }
        //await mqttClientPublisher.DisconnectAsync();
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error en 2" + ex);
        throw;
    }
}

The line 38 in the original code (here I have deleted the comments) is:

await mqttClientPublisher.ConnectAsync(optionsPublisher);

I’m using NuGet MQTTnet 3.0.5 and Net Core 2.1

Which project is your bug related to?

  • Client

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:13 (1 by maintainers)

github_iconTop GitHub Comments

3reactions
erikkjcommented, Aug 21, 2019

I have a similar issue in my code. I am using ManagedClient with reconnect delay = 10 seconds. Sporadic in my logs i see exceptions like this when the client disconnects:

2019-08-20 17:06:47.753 +00:00 [ERR] >> [2019-08-20T17:06:47.7478776Z] [187] [MqttClient] [Error]: Error while connecting with server.
MQTTnet.Exceptions.MqttCommunicationException: Cannot access a disposed object.
Object name: 'System.Net.Sockets.Socket'. ---> System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'System.Net.Sockets.Socket'.
   at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
   at System.Net.Sockets.Socket.<>c.<ConnectAsync>b__274_0(IAsyncResult iar)
--- End of stack trace from previous location where exception was thrown ---
   at MQTTnet.Implementations.MqttTcpChannel.ConnectAsync(CancellationToken cancellationToken)
   at MQTTnet.Internal.MqttTaskTimeout.WaitAsync(Func`2 action, TimeSpan timeout, CancellationToken cancellationToken)
   at MQTTnet.Adapter.MqttChannelAdapter.ConnectAsync(TimeSpan timeout, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at MQTTnet.Adapter.MqttChannelAdapter.WrapException(Exception exception)
   at MQTTnet.Adapter.MqttChannelAdapter.ConnectAsync(TimeSpan timeout, CancellationToken cancellationToken)
   at MQTTnet.Client.MqttClient.ConnectAsync(IMqttClientOptions options, CancellationToken cancellationToken)

The client is able to reconnect to the server most of the times, but sometimes the client “dies” and does not run anymore. The last log message from MQTTClient in my log when this happens is this:

2019-08-20 17:06:27.736 +00:00 [ERR] >> [2019-08-20T17:06:27.7217443Z] [174] [MqttClient] [Error]: Error while connecting with server.
MQTTnet.Exceptions.MqttCommunicationException: Connection refused []:8883 ---> System.Net.Internals.SocketExceptionFactory+ExtendedSocketException: Connection refused []:8883
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw(Exception source)
   at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
   at System.Net.Sockets.Socket.DoMultipleAddressConnectCallback(Object result, MultipleAddressConnectAsyncResult context)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw(Exception source)
   at System.Net.Sockets.Socket.DoMultipleAddressConnectCallback(Object result, MultipleAddressConnectAsyncResult context)
   at System.Net.Sockets.Socket.MultipleAddressConnectCallback(IAsyncResult result)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw(Exception source)
   at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
   at System.Net.Sockets.Socket.<>c.<ConnectAsync>b__274_0(IAsyncResult iar)
--- End of stack trace from previous location where exception was thrown ---
   at MQTTnet.Implementations.MqttTcpChannel.ConnectAsync(CancellationToken cancellationToken)
   at MQTTnet.Internal.MqttTaskTimeout.WaitAsync(Func`2 action, TimeSpan timeout, CancellationToken cancellationToken)
   at MQTTnet.Adapter.MqttChannelAdapter.ConnectAsync(TimeSpan timeout, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at MQTTnet.Adapter.MqttChannelAdapter.WrapException(Exception exception)
   at MQTTnet.Adapter.MqttChannelAdapter.ConnectAsync(TimeSpan timeout, CancellationToken cancellationToken)
   at MQTTnet.Client.MqttClient.ConnectAsync(IMqttClientOptions options, CancellationToken cancellationToken)
2019-08-20 17:06:33.405 +00:00 [DBG] Starting HttpMessageHandler cleanup cycle with 1 items
2019-08-20 17:06:33.407 +00:00 [DBG] Ending HttpMessageHandler cleanup cycle after 0.0099ms - processed: 0 items - remaining: 1 items
2019-08-20 17:06:37.734 +00:00 [DBG] >> [2019-08-20T17:06:37.7338579Z] [123] [MqttClient] [Verbose]: Trying to connect with server 'URL' (Timeout=00:00:10).
2019-08-20 17:06:43.404 +00:00 [DBG] Starting HttpMessageHandler cleanup cycle with 1 items
2019-08-20 17:06:43.411 +00:00 [DBG] Ending HttpMessageHandler cleanup cycle after 0.0099ms - processed: 0 items - remaining: 1 items
2019-08-20 17:06:47.753 +00:00 [ERR] >> [2019-08-20T17:06:47.7478776Z] [187] [MqttClient] [Error]: Error while connecting with server.
MQTTnet.Exceptions.MqttCommunicationException: Cannot access a disposed object.
Object name: 'System.Net.Sockets.Socket'. ---> System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'System.Net.Sockets.Socket'.
   at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
   at System.Net.Sockets.Socket.<>c.<ConnectAsync>b__274_0(IAsyncResult iar)
--- End of stack trace from previous location where exception was thrown ---
   at MQTTnet.Implementations.MqttTcpChannel.ConnectAsync(CancellationToken cancellationToken)
   at MQTTnet.Internal.MqttTaskTimeout.WaitAsync(Func`2 action, TimeSpan timeout, CancellationToken cancellationToken)
   at MQTTnet.Adapter.MqttChannelAdapter.ConnectAsync(TimeSpan timeout, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at MQTTnet.Adapter.MqttChannelAdapter.WrapException(Exception exception)
   at MQTTnet.Adapter.MqttChannelAdapter.ConnectAsync(TimeSpan timeout, CancellationToken cancellationToken)
   at MQTTnet.Client.MqttClient.ConnectAsync(IMqttClientOptions options, CancellationToken cancellationToken)
2019-08-20 17:06:47.755 +00:00 [DBG] >> [2019-08-20T17:06:47.7552332Z] [187] [MqttClient] [Verbose]: Disconnecting [Timeout=00:00:10]
1reaction
Feybcommented, Dec 17, 2019

also getting this even with the new MQTTnet 3.0.9-rc1, but its usually in a combination with a timeout. It does reconnect then i get like 2-3 messages, the same happens again and so on until the client dies.

> 2019-12-17 02:33:21.026 +00:00	[wrn]	Timeout while waiting for packet of type 'MqttPingRespPacket'.	[MQTTnet.MqttClient]
> 2019-12-17 02:33:21.031 +00:00	[wrn]	Communication error while sending/receiving keep alive packets.	[MQTTnet.MqttClient]
> MQTTnet.Exceptions.MqttCommunicationTimedOutException: Exception of type 'MQTTnet.Exceptions.MqttCommunicationTimedOutException' was thrown.
>    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
>    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
>    at MQTTnet.PacketDispatcher.MqttPacketAwaiter`1.<WaitOneAsync>d__4.MoveNext()
> --- End of stack trace from previous location where exception was thrown ---
>    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
>    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
>    at MQTTnet.Client.MqttClient.<SendAndReceiveAsync>d__46`1.MoveNext()
> --- End of stack trace from previous location where exception was thrown ---
>    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
>    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
>    at MQTTnet.Client.MqttClient.<TrySendKeepAliveMessagesAsync>d__47.MoveNext()
> 2019-12-17 02:33:21.423 +00:00	[wrn]	Disconnected	[.....Services.MqttClient]
> 2019-12-17 02:33:21.426 +00:00	[wrn]	Communication error while receiving packets.	[MQTTnet.MqttClient]
> MQTTnet.Exceptions.MqttCommunicationException: Cannot access a disposed object.
> Object name: 'System.Net.Sockets.NetworkStream'. ---> System.ObjectDisposedException: Cannot access a disposed object.
> Object name: 'System.Net.Sockets.NetworkStream'.
>    at System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult)
>    at System.IO.Stream.<>c.<BeginEndReadAsync>b__43_1(Stream stream, IAsyncResult asyncResult)
>    at System.Threading.Tasks.TaskFactory`1.FromAsyncTrimPromise`1.Complete(TInstance thisRef, Func`3 endMethod, IAsyncResult asyncResult, Boolean requiresSynchronization)
> --- End of stack trace from previous location where exception was thrown ---
>    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
>    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
>    at MQTTnet.Implementations.MqttTcpChannel.<ReadAsync>d__17.MoveNext()
> --- End of stack trace from previous location where exception was thrown ---
>    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
>    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
>    at MQTTnet.Formatter.MqttPacketReader.<ReadFixedHeaderAsync>d__3.MoveNext()
> --- End of stack trace from previous location where exception was thrown ---
>    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
>    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
>    at MQTTnet.Adapter.MqttChannelAdapter.<ReceiveAsync>d__37.MoveNext()
> --- End of stack trace from previous location where exception was thrown ---
>    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
>    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
>    at MQTTnet.Adapter.MqttChannelAdapter.<ReceivePacketAsync>d__35.MoveNext()
>    --- End of inner exception stack trace ---
>    at MQTTnet.Adapter.MqttChannelAdapter.WrapException(Exception exception)
>    at MQTTnet.Adapter.MqttChannelAdapter.<ReceivePacketAsync>d__35.MoveNext()
> --- End of stack trace from previous location where exception was thrown ---
>    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
>    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
>    at MQTTnet.Client.MqttClient.<TryReceivePacketsAsync>d__48.MoveNext()
> 2019-12-17 02:33:21.427 +00:00	[wrn]	Disconnected	[.....Services.MqttClient]
Read more comments on GitHub >

github_iconTop Results From Across the Web

MQTTnet.Exceptions.MqttCommunicationException: ...
MQTTnet.Exceptions.MqttCommunicationException: Cannot access a disposed object Object name: 'System.Net.Sockets.Socket'. ---> System.
Read more >
MQTTnet - Cannot access a disposed object
Hello,. I have a task with a parallel.ForEach ( I have also tried with a simple foreach) Parallel.ForEach(receiveMessageResponse.
Read more >
Cannot access a disposed object" on MqttClient.DisconnectAsync()
NET Version: Framework 4.7.2 MQTTnet nuget Version: 3.0.5. I have a sporadically occurring problem when calling the Method IMqttClient.DisconnectAsync() .
Read more >
Cannot access a disposed object. A common cause of this ...
A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the...
Read more >
ObjectDisposedException in M2Mqtt Event Handler of ASP. ...
System.ObjectDisposedException: "Cannot access a disposed object. I can call the repository from a controller and it works fine. How can I get ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found