[CSHARP-1446] Uncought task exception when connection timeout occurs Created: 16/Oct/15  Updated: 05/Apr/19  Resolved: 16/Oct/15

Status: Closed
Project: C# Driver
Component/s: Connectivity
Affects Version/s: 2.0, 2.0.1
Fix Version/s: None

Type: Task Priority: Blocker - P1
Reporter: Philipp Hebing Assignee: Unassigned
Resolution: Done Votes: 0
Labels: Bug, UnobservedTaskException, driver, exception, question, unhandled
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

After creating a MongoClient and getting the Database with
var client = new MongoClient(location);
database = client.GetDatabase(databaseName);
the client automatically tries to connect to the server of the location string. If the server is present everything works fine, but if the connection can not be established an uncaught task exception is raised:
"System.AggregateException: Ausnahmen einer Aufgabe wurden nicht überwacht (entweder wegen Wartens auf die Aufgabe oder wegen des Zugriffs auf die Ausnahmeeigenschaft. Daher wurde die nicht überwachte Ausnahme vom Finalizer-Thread erneut ausgelöst. ---> System.TimeoutException: A timeout occured after 30000ms selecting a server using CompositeServerSelector{ Selectors = ReadPreferenceServerSelector{ ReadPreference =

{ Mode = Primary, TagSets = System.Collections.Generic.List`1[MongoDB.Driver.TagSet] }

}, LatencyLimitingServerSelector

{ AllowedLatencyRange = 00:00:00.0150000 }

}. Client view of cluster state is { ClusterId : "1", Type : "Unknown", State : "Disconnected", Servers : [{ ServerId: "

{ ClusterId : 1, EndPoint : "Unspecified/localhost:27017" }

", EndPoint: "Unspecified/localhost:27017", State: "Disconnected", Type: "Unknown", HeartbeatException: "MongoDB.Driver.MongoConnectionException: An exception occurred while opening a connection to the server. ---> System.Net.Sockets.SocketException: Es konnte keine Verbindung hergestellt werden, da der Zielcomputer die Verbindung verweigerte 127.0.0.1:27017 ..."
and catched by our UnobservedTaskExceptionEventHandler (
TaskScheduler.UnobservedTaskException += UnobservedTaskExceptionEventHandler.
Since we do not want to continue work after unobserved task exception in our system, the normal behaviour is to shut down and restart the application.
Is there a way to avoid the exception? Since the Task can not be reached from outside the driver, we do not see a way to catch it before the task gets out of reach and the exception is handed to the handler by the garbagecollector.
As a workaround we modified the Handler to not restart on TimeoutExceptions, but we would appreciate a different solution.



 Comments   
Comment by Craig Wilson [ 16/Oct/15 ]

Thanks Philipp... Please re-open if that turns out to not be the issue.

Comment by Philipp Hebing [ 16/Oct/15 ]

Well i think i found the problem by myself now:
if (database.ListCollectionsAsync().Wait(10000))
returns before the Async Task throws the 30 seconds TimeoutException. The Task goes out of scope and the Exception is rethrown by the GC.
I think this ticket can be closed. Thanks anyway

Comment by Philipp Hebing [ 16/Oct/15 ]

This console application causes the error. Since the error only occures when the Task is collected by the GC you have to let the program run for a bit and wait (about 2 Minutes).
The Mongoserver has to be offline, so i do not think details would help but we normally use mongos.

class Program
    {
 
        private static IMongoDatabase database;
        private static System.Threading.Timer checkConnectionTimer;
 
 
        static void Main(string[] args)
        {
            TaskScheduler.UnobservedTaskException += UnobservedTaskExceptionEventHandler;
            checkConnectionTimer = new System.Threading.Timer(CheckConnectionCallback, null, 10000, Timeout.Infinite);
 
            try
            {
                var client = new MongoClient("mongodb://username:pass@localhost");
                database = client.GetDatabase("Test");
                Console.WriteLine("Client is now connecting.");
            }
            catch (MongoConfigurationException e)
            {
                throw new ArgumentException("Error: " + e.Message);
            }
 
            Console.ReadKey();
 
            if (checkConnectionTimer != null)
            {
                checkConnectionTimer.Dispose();
            }
        }
 
        private static void CheckConnectionCallback(object state)
        {
            try
            {
                if (database.ListCollectionsAsync().Wait(10000))
                {
                    Console.WriteLine("Connected.");
                }
                else
                {
                    Console.WriteLine("Not Connected.");
                }
            }
            catch (AggregateException)
            {
                Console.WriteLine("Not Connected (Exception).");
            }
            finally
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
                Console.WriteLine("GC Run done.");
            }
 
            if (checkConnectionTimer != null)
            {
                try
                {
                    //restart timer
                    checkConnectionTimer.Change(10000, Timeout.Infinite);
                }
                catch (ObjectDisposedException)
                {
                    return;
                }
            }
        }
 
        private static void UnobservedTaskExceptionEventHandler(object sender, UnobservedTaskExceptionEventArgs e)
        {
            Console.Out.WriteLine("Uncaught task exception!!!", e.Exception);
        }
    }
}

(sorry for bad formating but i am kind of in a rush)
Philipp

Comment by Craig Wilson [ 16/Oct/15 ]

Hi Philipp,

Can you provide some more details. I've attempted to reproduce this in a simple Console application, but no unobserved exception showed up. What type of application is this? Are you connecting to a standalone, replica set, or mongos'? Is it possible to provide a simple repro of the problem?

Craig

Generated at Wed Feb 07 21:39:38 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.