[CSHARP-1288] System.ObjectDisposedException error while querying all documents with Mongo C# driver Created: 21/May/15  Updated: 09/Mar/16  Resolved: 09/Mar/16

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

Type: Bug Priority: Major - P3
Reporter: nina qiu Assignee: Craig Wilson
Resolution: Done Votes: 0
Labels: driver, replicaset, windows
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Two windows server 2012 datacenter virtual machines, deployed a cluster of 1 primary, 2 secondaries.(one node in a machine, another two nodes in another machine).
MongoDb version is 3.0.2, c# driver is latest 2.0.0.


Issue Links:
Duplicate
duplicates CSHARP-1283 Remove from the topology a replica se... Closed

 Description   

We are using lateast Mongodb c# driver(2.0.0) which is downloaded through nuget to connect to a MongoDB replicaset(3.0.2).

From time to time, the driver will throw an exception "Cannot access a disposed object.Object name: 'ClusterableServer'." while we quering all the documents if we set the readPreference to primaryPreferred or secondary or secondaryPreferred.

Detail exception: at MongoDB.Driver.Core.Servers.ClusterableServer.ThrowIfDisposed() at MongoDB.Driver.Core.Servers.ClusterableServer.ThrowIfNotOpen() at MongoDB.Driver.Core.Servers.ClusterableServer.d__0.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 System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult()
at MongoDB.Driver.Core.Operations.AsyncCursor1.d__0.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 System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult()
at MongoDB.Driver.Core.Operations.AsyncCursor1.d__b.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 System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
at MongoDB.Driver.Sync.AsyncCursorEnumeratorAdapter1.d__0.MoveNext() at System.Collections.Generic.List1..ctor(IEnumerable1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source) at TryMongoReplica.Program.Main(String[] args) in d:\Practice\TryMongoReplica\TryMongoReplica\Program.cs:line 47 at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart()



 Comments   
Comment by Craig Wilson [ 27/Jan/16 ]

Nina,

Have you been having any further issues with this... I spent a little time attempting to figure this out and was not able to reproduce it. However, after thinking about it more, it may be related to the fact that the servers listed in your connection string are not the ones in your replica set configuration. If you'd like to proceed with this issue, please try using the hostnames of the servers listed in your replica set configuration rather than ip addresses. Let me know what you'd like to do.

Craig

Comment by Craig Wilson [ 26/May/15 ]

Ok, good. That goes back to my original prognosis, although I'm not exactly sure why it is happening. I'm going to spend some time attempting to reproduce this. Until then, you should catch these exceptions and ignore them.

Comment by nina qiu [ 26/May/15 ]

Thanks Graig, the error only occurs at the beginning of the program, and after that it is ok.

Comment by Craig Wilson [ 25/May/15 ]

Thanks Nina,

I've taken your code and added a try/catch and a while loop. I'd like to see if the error only occurs at the beginning of the program, or if it persists throughout. Let this run for about a minute before cutting it off.

static void Main(string[] args)
    {
 
        string connectionString = @"mongodb://10.156.64.48:27018,10.156.68.81:27019,10.156.68.81:27020/?replicaSet=myset&readPreference=secondary";
        MongoUrl url = new MongoUrl(connectionString);
        MongoClient client = new MongoClient(url);
 
        var mongoServer = client.GetServer();
        string dbName = "test";
        MongoDatabase database = mongoServer.GetDatabase(dbName);
 
        string collectionName = "Notes";
        MongoCollection<Note1> notes = database.GetCollection<Note1>(collectionName);
 
        while(true)
        {
            try
            {
                var foundAllNotes = notes.FindAllAs<Note1>().ToList();
                Console.WriteLine("found all note:");
         
                foreach (var foundAllNote in foundAllNotes)
                {
                    string output = string.Format("Id:{0}, Text:{1}, Date: {2}", foundAllNote.Id, foundAllNote.Text,
                        foundAllNote.Date);
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex);
            }
 
            Thread.Sleep(1000);
        }
 
        Console.ReadKey();
    }

Thanks,
Craig

Comment by nina qiu [ 25/May/15 ]

Here pasted my code, the exception happens at var foundAllNotes = notes.FindAllAs<Note1>().ToList();:

    static void Main(string[] args)
    {
 
        string connectionString = @"mongodb://10.156.64.48:27018,10.156.68.81:27019,10.156.68.81:27020/?replicaSet=myset&readPreference=secondary";
        MongoUrl url = new MongoUrl(connectionString);
        MongoClient client = new MongoClient(url);
 
        var mongoServer = client.GetServer();
        string dbName = "test";
        MongoDatabase database = mongoServer.GetDatabase(dbName);
 
        string collectionName = "Notes";
        MongoCollection<Note1> notes = database.GetCollection<Note1>(collectionName);
 
        var foundAllNotes = notes.FindAllAs<Note1>().ToList();
        Console.WriteLine("found all note:");
 
        foreach (var foundAllNote in foundAllNotes)
        {
            string output = string.Format("Id:{0}, Text:{1}, Date: {2}", foundAllNote.Id, foundAllNote.Text,
                foundAllNote.Date);
        }
 
        Console.ReadKey();
    }

Thanks,
Nina

Comment by nina qiu [ 24/May/15 ]

No, these errors do not go away, the application crashes after the exception is thrown.

Thanks,
Nina

Comment by Craig Wilson [ 22/May/15 ]

Thanks. This isn't what I thought it was. Just to confirm, these errors happen at startup, but then go away?

Comment by nina qiu [ 22/May/15 ]

Sure,
myset:PRIMARY> rs.conf()
{
"_id" : "myset",
"version" : 1,
"members" : [
{
"_id" : 0,
"host" : "10.156.64.48:27018",
"arbiterOnly" : false,
"buildIndexes" : true,
"hidden" : false,
"priority" : 1,
"tags" : {

},
"slaveDelay" : 0,
"votes" : 1
},
{
"_id" : 1,
"host" : "10.156.68.81:27019",
"arbiterOnly" : false,
"buildIndexes" : true,
"hidden" : false,
"priority" : 1,
"tags" : {

},
"slaveDelay" : 0,
"votes" : 1
},
{
"_id" : 2,
"host" : "10.156.68.81:27020",
"arbiterOnly" : false,
"buildIndexes" : true,
"hidden" : false,
"priority" : 1,
"tags" : {

},
"slaveDelay" : 0,
"votes" : 1
}
],
"settings" : {
"chainingAllowed" : true,
"heartbeatTimeoutSecs" : 10,
"getLastErrorModes" : {

},
"getLastErrorDefaults" :

{ "w" : 1, "wtimeout" : 0 }

}
}

Thanks,
Nina

Comment by Craig Wilson [ 22/May/15 ]

Interesting, that wasn't what I was expecting to see.

Could you provide the results of "rs.config()" instead of "rs.status()"?

Comment by nina qiu [ 22/May/15 ]

Here is the rs.status() result:
myset:PRIMARY> rs.status()
{
"set" : "myset",
"date" : ISODate("2015-05-22T02:06:30.476Z"),
"myState" : 1,
"members" : [

{ "_id" : 0, "name" : "10.156.64.48:27018", "health" : 1, "state" : 2, "stateStr" : "SECONDARY", "uptime" : 225, "optime" : Timestamp(1432216122, 159), "optimeDate" : ISODate("2015-05-21T13:48:42Z"), "lastHeartbeat" : ISODate("2015-05-22T02:06:29.452Z"), "lastHeartbeatRecv" : ISODate("2015-05-22T02:06:29.266Z" ), "pingMs" : 0, "configVersion" : 1 }

,

{ "_id" : 1, "name" : "10.156.68.81:27019", "health" : 1, "state" : 1, "stateStr" : "PRIMARY", "uptime" : 231, "optime" : Timestamp(1432216122, 159), "optimeDate" : ISODate("2015-05-21T13:48:42Z"), "electionTime" : Timestamp(1432260165, 1), "electionDate" : ISODate("2015-05-22T02:02:45Z"), "configVersion" : 1, "self" : true }

,

{ "_id" : 2, "name" : "10.156.68.81:27020", "health" : 1, "state" : 2, "stateStr" : "SECONDARY", "uptime" : 224, "optime" : Timestamp(1432216122, 159), "optimeDate" : ISODate("2015-05-21T13:48:42Z"), "lastHeartbeat" : ISODate("2015-05-22T02:06:30.267Z"), "lastHeartbeatRecv" : ISODate("2015-05-22T02:06:30.307Z" ), "pingMs" : 0, "configVersion" : 1 }

],
"ok" : 1
}

Comment by nina qiu [ 22/May/15 ]

Thanks Craig! Since I'm new to MongoDB, I cannot understand your meanings clearly.
Here pasted my replica config and my connection string, could you kindly point out which part should I modify?

Machine 10.156.68.81:
Node 10.156.68.81:27019 config
storage:
dbPath: D:\mongodb\data02
journal:
enabled: true
net:
port: 27019
replication:
replSetName: myset

Node 10.156.68.81:27020 config
storage:
dbPath: D:\mongodb\data03
journal:
enabled: true
net:
port: 27020
replication:
replSetName: myset

Machine 10.156.64.48:
storage:
dbPath: D:\mongodb\data01
journal:
enabled: true
net:
port: 27018
replication:
replSetName: myset

My connection string in C#:
string connectionString = @"mongodb://10.156.64.48:27018,10.156.68.81:27019,10.156.68.81:27020/?replicaSet=myset&readPreference=secondary";

Thanks,
Nina

Comment by Craig Wilson [ 21/May/15 ]

nina,

This happens because your seed list does not contain the same hosts that are in your replica set config. So, we allow you to start doing stuff only to find that the node we are talking to is known by a different name, so we drop him (dispose) and create a new one. I've linked CSHARP-1283 which will fix this problem. Until then, the best thing to do is to make sure your seedlist contains the same hosts as your replica set config.

Craig

Comment by nina qiu [ 21/May/15 ]

Hi Craig, thank you for you quick response. This exception happens immediately after startup with high frequency.

Thanks,
Nina

Comment by Craig Wilson [ 21/May/15 ]

Hi nina,

This certainly shouldn't be happening. I can guess at what is happening here, but I need a little more information.

Does this happen immediately after startup, or does it sometimes happen long after the program has been running?

Craig

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