Skip to content

Commit e7b2664

Browse files
committed
CSHARP-1227: fixed race condition between server disposal and heartbeat requests.
1 parent f589388 commit e7b2664

File tree

2 files changed

+30
-4
lines changed

2 files changed

+30
-4
lines changed

src/MongoDB.Driver.Core/Core/Clusters/Cluster.cs

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ protected Cluster(ClusterSettings settings, IClusterableServerFactory serverFact
6666
_description = ClusterDescription.CreateInitial(_clusterId, _settings.ConnectionMode.ToClusterType());
6767
_descriptionChangedTaskCompletionSource = new TaskCompletionSource<bool>();
6868

69-
_rapidHeartbeatTimer = new Timer(o => RequestHeartbeat(), null, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
69+
_rapidHeartbeatTimer = new Timer(RapidHeartbeatTimerCallback, null, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
7070
}
7171

7272
// events
@@ -159,6 +159,20 @@ public virtual void Initialize()
159159
_state.TryChange(State.Initial, State.Open);
160160
}
161161

162+
private void RapidHeartbeatTimerCallback(object args)
163+
{
164+
try
165+
{
166+
RequestHeartbeat();
167+
}
168+
catch
169+
{
170+
// TODO: Trace this
171+
// If we don't protect this call, we could
172+
// take down the app domain.
173+
}
174+
}
175+
162176
protected abstract void RequestHeartbeat();
163177

164178
protected void OnDescriptionChanged(ClusterDescription oldDescription, ClusterDescription newDescription)
@@ -188,14 +202,14 @@ public async Task<IServer> SelectServerAsync(IServerSelector selector, Cancellat
188202
if (_settings.PreServerSelector != null || _settings.PostServerSelector != null)
189203
{
190204
var allSelectors = new List<IServerSelector>();
191-
if(_settings.PreServerSelector != null)
205+
if (_settings.PreServerSelector != null)
192206
{
193207
allSelectors.Add(_settings.PreServerSelector);
194208
}
195209

196210
allSelectors.Add(selector);
197211

198-
if(_settings.PostServerSelector != null)
212+
if (_settings.PostServerSelector != null)
199213
{
200214
allSelectors.Add(_settings.PostServerSelector);
201215
}

src/MongoDB.Driver.Core/Core/Clusters/MultiServerCluster.cs

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,19 @@ protected override void RequestHeartbeat()
169169
{
170170
if (server.IsInitialized)
171171
{
172-
server.RequestHeartbeat();
172+
try
173+
{
174+
server.RequestHeartbeat();
175+
}
176+
catch (ObjectDisposedException)
177+
{
178+
// There is a possible race condition here
179+
// due to the fact that we are working
180+
// with the server outside of the lock,
181+
// meaning another thread could remove
182+
// the server and dispose of it before
183+
// we invoke the method.
184+
}
173185
}
174186
}
175187
}

0 commit comments

Comments
 (0)