Uploaded image for project: 'C# Driver'
  1. C# Driver
  2. CSHARP-3684

Unobserved task exception when connection times out



    • Bug
    • Status: Closed
    • Unknown
    • Resolution: Duplicate
    • 2.12.0, 2.12.1, 2.12.2, 2.12.3
    • None
    • None
    • None


      When an established connection is interrupted, it will cause an unobserved task exception to be thrown, in the latest version of the package.
      While mostly harmless, this pollutes logs and might confuse the end users, as such I believe these exceptions should be handled or muted.
      This new behavior started on versions 2.12.x

      Thrown Exception (Full stack trace attached):

      System.AggregateException: A Task's exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was rethrown by the finalizer thread. ---> MongoDB.Driver.MongoConnectionException: An exception occurred while receiving a message from the server. ---> System.IO.IOException: Unable to read data from the transport connection: An established connection was aborted by the software in your host machine. ---> System.Net.Sockets.SocketException: An established connection was aborted by the software in your host machine
         at System.Net.Sockets.Socket.EndReceive(IAsyncResult asyncResult)
         at System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult)


      It can be reproduced with the following .Net Framework Console app:

      public static class Program {
      public static async Task Main() {
         TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
         var mongoClient = new MongoClient("mongodb+srv://username:password@instance.mongodb.net/Database");
         var database = mongoClient.GetDatabase("Database");
         var collection = database.GetCollection<object>("Collection");
         var count = await collection.CountDocumentsAsync(f => true);
         Console.WriteLine($"Document count: {count}");
         Console.WriteLine("Stop server or disconnect from the internet now");
         try {
            var count2 = await collection.CountDocumentsAsync(f => true);
            Console.WriteLine($"Document count: {count2}");
         } catch {
            // Do nothing, this is expected to fail
      private static void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e) {
         // This should never be called, but it is
         Console.WriteLine($"UnobservedTaskException: {sender.GetType()}\n{e.Exception}");


        Issue Links



              mikalai.mazurenka@mongodb.com Mikalai Mazurenka (Inactive)
              laura.neto@deptagency.com Laura Fernandes Nóbrega Neto
              0 Vote for this issue
              2 Start watching this issue