Simple c# console program wont close after `var mc = new MongoClient(connStr);`

This is a reduced version of the netcore3.1 console app that is having the issue in the title.

private static string MongoDbConnectionString => 

public static void Main()
    var mongoClient = new MongoClient(MongoDbConnectionString);
    Console.WriteLine("All operations completed");

There are other statements in the actual Main() function, but they are all commented out except for these two. With the project this code belongs to set as startup project in VS and then started, the program runs and displays the “All operations completed” message in the console window, but the program does not exit. If i comment out the var mongoClient... statement, the program displays the “All operations completed” message briefly before the console window that was opened by the debugging session closes.

When the program is not closing, if I pause the execution and inspect the running tasks (Debug -> Windows -> Tasks) to see what may be active, there are over 200 tasks that are active. Most of them are ones like these, but in varying orders.

TaskID   Status     Location                                                                                                                   Task
1324	Awaiting	MongoDB.Driver.Core.Servers.ServerMonitor.GetIsMasterResultAsync(connection, isMasterProtocol, cancellationToken)								MongoDB.Driver.Core.Servers.ServerMonitor.GetIsMasterResultAsync(connection, isMasterProtocol, cancellationToken)
1323	Awaiting	MongoDB.Driver.Core.Connections.IsMasterHelper.GetResultAsync(connection, isMasterProtocol, cancellationToken)									MongoDB.Driver.Core.Connections.IsMasterHelper.GetResultAsync(connection, isMasterProtocol, cancellationToken)
1322	Awaiting	MongoDB.Driver.Core.WireProtocol.CommandUsingCommandMessageWireProtocol<TCommandResult>.ExecuteAsync(connection, cancellationToken)				MongoDB.Driver.Core.WireProtocol.CommandUsingCommandMessageWireProtocol<TCommandResult>.ExecuteAsync(connection, cancellationToken)
1321	Awaiting	MongoDB.Driver.Core.Connections.BinaryConnection.ReceiveMessageAsync(responseTo, encoderSelector, messageEncoderSettings, cancellationToken)	MongoDB.Driver.Core.Connections.BinaryConnection.ReceiveMessageAsync(responseTo, encoderSelector, messageEncoderSettings, cancellationToken)
1320	Awaiting	MongoDB.Driver.Core.Connections.BinaryConnection.ReceiveBufferAsync(responseTo, cancellationToken)												MongoDB.Driver.Core.Connections.BinaryConnection.ReceiveBufferAsync(responseTo, cancellationToken)
1319	Awaiting	MongoDB.Driver.Core.Connections.BinaryConnection.ReceiveBufferAsync(cancellationToken)															MongoDB.Driver.Core.Connections.BinaryConnection.ReceiveBufferAsync(cancellationToken)
1318	Awaiting	MongoDB.Driver.Core.Misc.StreamExtensionMethods.ReadBytesAsync(stream, buffer, offset, count, timeout, cancellationToken)						MongoDB.Driver.Core.Misc.StreamExtensionMethods.ReadBytesAsync(stream, buffer, offset, count, timeout, cancellationToken)
1317	Awaiting	MongoDB.Driver.Core.Misc.StreamExtensionMethods.ReadAsync(stream, buffer, offset, count, timeout, cancellationToken)							MongoDB.Driver.Core.Misc.StreamExtensionMethods.ReadAsync(stream, buffer, offset, count, timeout, cancellationToken)
1316	Awaiting	System.Net.Security.SslStream.ReadAsyncInternal<TReadAdapter>(adapter, buffer)																	System.Net.Security.SslStream.ReadAsyncInternal<TReadAdapter>(adapter, buffer)

In no place in my code am I using any Async, so any tasks that are created are going to be from the mongodb c# driver or the .net core runtime. I created a minidump from the process when its having this condition, but I’m not going to upload it where the general public can get to it.

Why is the MongoClient lacking any kind of explicit Disconnect() or Dispose()?
How can I get this to shutdown cleanly?

I tested this out in RoslynPad to rule out Visual Studio and it does the same thing there. After changing the package versions this program will exit correctly up to v2.8.1, but v2.9.0 will start the described issue

You can try this: mongoClient.Cluster.Dispose();. Though the documentation doesn’'t explicitly says the program needs to close the connection explicitly (I believe the closing of the connection is automatic).

What is the MongoDbConnectionString you are working with?

The connection string (redacted) is like


Using the mongoClient.Cluster.Dispose(); at the end does indeed stop the RoslynPad example program from lingering open. Any idea why it would stay open in the first place?
The VS console application still lingers when this is added into the finally block.

I got same problem on a .net core backgroudservice. I need to close the app so I do a _hostApplicationLifetime.StopApplication(); in finally bloc but the processus don’t stop and I see these processes are waiting :

The fact is my program close normally when i connect to a replicaset cluster but not when i connect to a sharded cluster… I have tried in v2.10.4 and v2.11.2 ( mongodb v4.2)
Any idea why in replicaset mongo environmnet everything’is ok but not in sharded mongo environment ?

I am having this exact same problem using MongDB.Driver 2.11.6, on commandline using mono built with msbuild 16.1.85. While it’s fine on my laptop, it hangs the same way on server. I can’t debug it due to lack of GDB but running mono with ‘–trace’ shows a metric buttload of bson-related activity in a thread after the main thread has exited

BTW the problem didn’t go away when I added a call to mongoClient.Cluster.Dispose()

Hi Andrew,
We will be tracking this issue in the Jira ticket:

1 Like