// internal methods internal MongoConnection AcquireConnection(ReadPreference readPreference) { MongoConnection requestConnection = null; lock (_serverLock) { // if a thread has called RequestStart it wants all operations to take place on the same connection int threadId = Thread.CurrentThread.ManagedThreadId; Request request; if (_requests.TryGetValue(threadId, out request)) { if (!readPreference.MatchesInstance(request.Connection.ServerInstance)) { throw new InvalidOperationException("The thread is in a RequestStart and the current server instance is not a match for the supplied read preference."); } requestConnection = request.Connection; } } // check authentication outside of lock if (requestConnection != null) { return(requestConnection); } var serverInstance = _serverProxy.ChooseServerInstance(readPreference); return(serverInstance.AcquireConnection()); }
/// <summary> /// Lets the server know that this thread is about to begin a series of related operations that must all occur /// on the same connection. The return value of this method implements IDisposable and can be placed in a /// using statement (in which case RequestDone will be called automatically when leaving the using statement). /// </summary> /// <param name="initialDatabase">One of the databases involved in the related operations.</param> /// <param name="readPreference">The read preference.</param> /// <returns>A helper object that implements IDisposable and calls <see cref="RequestDone"/> from the Dispose method.</returns> public virtual IDisposable RequestStart(MongoDatabase initialDatabase, ReadPreference readPreference) { int threadId = Thread.CurrentThread.ManagedThreadId; lock (_serverLock) { Request request; if (_requests.TryGetValue(threadId, out request)) { if (!readPreference.MatchesInstance(request.Connection.ServerInstance)) { throw new InvalidOperationException("A nested call to RequestStart was made and the current instance does not match the nested read preference."); } request.NestingLevel++; return(new RequestStartResult(this)); } } var serverInstance = _serverProxy.ChooseServerInstance(readPreference); var connection = serverInstance.AcquireConnection(); lock (_serverLock) { var request = new Request(connection); _requests.Add(threadId, request); return(new RequestStartResult(this)); } }