Skip to content

Commit 357e25f

Browse files
author
rstam
committed
CSHARP-508: VerifyState and VerifyUnknownStates now make a copy of the instances collection so that they can iterate over the instances safely.
1 parent 2960289 commit 357e25f

File tree

2 files changed

+27
-4
lines changed

2 files changed

+27
-4
lines changed

Driver/Core/MongoServer.cs

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1152,9 +1152,19 @@ public virtual void VerifyState()
11521152
{
11531153
lock (_serverLock)
11541154
{
1155-
foreach (var instance in _instances)
1155+
var instances = Instances; // create a copy that we can safely iterate over
1156+
foreach (var instance in instances)
11561157
{
1157-
instance.VerifyState();
1158+
bool isInstanceStillValid;
1159+
lock (_stateLock)
1160+
{
1161+
isInstanceStillValid = _instances.Contains(instance);
1162+
}
1163+
1164+
if (isInstanceStillValid)
1165+
{
1166+
instance.VerifyState();
1167+
}
11581168
}
11591169
}
11601170
}
@@ -1421,9 +1431,16 @@ private void VerifyUnknownStates()
14211431
{
14221432
lock (_serverLock)
14231433
{
1424-
foreach (var instance in _instances)
1434+
var instances = Instances; // create a copy that we can safely iterate over
1435+
foreach (var instance in instances)
14251436
{
1426-
if (instance.State == MongoServerState.Unknown)
1437+
bool isInstanceStillValid;
1438+
lock (_stateLock)
1439+
{
1440+
isInstanceStillValid = _instances.Contains(instance);
1441+
}
1442+
1443+
if (isInstanceStillValid && instance.State == MongoServerState.Unknown)
14271444
{
14281445
instance.VerifyState();
14291446
}

DriverUnitTests/Core/MongoServerTests.cs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -287,6 +287,12 @@ public void TestSecondaries()
287287
Assert.AreEqual(0, _server.Secondaries.Length);
288288
}
289289

290+
[Test]
291+
public void TestVerifyState()
292+
{
293+
_server.VerifyState();
294+
}
295+
290296
[Test]
291297
public void TestVersion()
292298
{

0 commit comments

Comments
 (0)