MQTTnet.Exceptions.MqttCommunicationException: Cannot access a disposed object
See original GitHub issueHello,
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:
- Created 4 years ago
- Comments:13 (1 by maintainers)
Top 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 >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found

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:
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:
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.