Skip to content

Commit 34bbb5b

Browse files
author
rstam
committed
CSHARP-574: special case single matching instance and put lock around call to Random.Next.
1 parent 2d59d0d commit 34bbb5b

File tree

2 files changed

+19
-5
lines changed

2 files changed

+19
-5
lines changed

Driver/Internal/ReplicaSetMongoServerProxy.cs

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -234,10 +234,17 @@ private MongoServerInstance GetMatchingInstance(List<ConnectedInstanceCollection
234234
}
235235

236236
// stop looking at tagSets if this one yielded any matching instances
237-
if (matchingInstances.Count != 0)
237+
if (matchingInstances.Count == 1)
238238
{
239-
var index = _random.Next(matchingInstances.Count);
240-
return matchingInstances[index]; // randomly selected matching instance
239+
return matchingInstances[0];
240+
}
241+
else if (matchingInstances.Count != 0)
242+
{
243+
lock (_randomLock)
244+
{
245+
var index = _random.Next(matchingInstances.Count);
246+
return matchingInstances[index]; // randomly selected matching instance
247+
}
241248
}
242249
}
243250

Driver/Internal/ShardedMongoServerProxy.cs

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -64,14 +64,21 @@ protected override MongoServerInstance ChooseServerInstance(ConnectedInstanceCol
6464
{
6565
return null;
6666
}
67+
else if (instancesWithPingTime.Count == 1)
68+
{
69+
return instancesWithPingTime[0].Instance;
70+
}
6771
else
6872
{
6973
var secondaryAcceptableLatency = Server.Settings.SecondaryAcceptableLatency;
7074
var minPingTime = instancesWithPingTime[0].CachedAveragePingTime;
7175
var maxPingTime = minPingTime + secondaryAcceptableLatency;
7276
var n = instancesWithPingTime.Count(i => i.CachedAveragePingTime <= maxPingTime);
73-
var index = _random.Next(n);
74-
return instancesWithPingTime[index].Instance; // return random instance
77+
lock (_randomLock)
78+
{
79+
var index = _random.Next(n);
80+
return instancesWithPingTime[index].Instance; // return random instance
81+
}
7582
}
7683
}
7784

0 commit comments

Comments
 (0)