Skip to content

Commit db8e0a4

Browse files
committed
Catch all exceptions in HeartbeatWriteTimerCallback and HeartbeatReadTimerCallback to avoid crash
1 parent d18e312 commit db8e0a4

File tree

1 file changed

+18
-21
lines changed

1 file changed

+18
-21
lines changed

projects/RabbitMQ.Client/Impl/Connection.Heartbeat.cs

Lines changed: 18 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -80,17 +80,19 @@ private void NotifyHeartbeatListener()
8080
_heartbeatDetected = true;
8181
}
8282

83+
// Intentionally declared `async void` because `System.Threading.Timer` requires a void callback.
84+
// Catch all exceptions in it: any exceptions unhandled by the method might lead to the process crash
8385
private async void HeartbeatReadTimerCallback(object? state)
8486
{
85-
if (_heartbeatReadTimer is null)
87+
try
8688
{
87-
return;
88-
}
89+
if (_heartbeatReadTimer is null)
90+
{
91+
return;
92+
}
8993

90-
bool shouldTerminate = false;
94+
bool shouldTerminate = false;
9195

92-
try
93-
{
9496
if (false == _closed)
9597
{
9698
if (_heartbeatDetected)
@@ -131,34 +133,29 @@ await FinishCloseAsync(cts.Token)
131133
_heartbeatReadTimer?.Change((int)Heartbeat.TotalMilliseconds, Timeout.Infinite);
132134
}
133135
}
134-
catch (OperationCanceledException)
135-
{
136-
if (false == _mainLoopCts.IsCancellationRequested)
137-
{
138-
throw;
139-
}
140-
}
141136
catch (ObjectDisposedException)
142137
{
143138
// timer is already disposed,
144139
// e.g. due to shutdown
145140
}
146-
catch (NullReferenceException)
141+
catch (Exception)
147142
{
148-
// timer has already been disposed from a different thread after null check
149-
// this event should be rare
143+
// ignore
144+
// peer unavailability. See rabbitmq/rabbitmq-dotnet-client#638 for details.
150145
}
151146
}
152147

148+
// Intentionally declared `async void` because `System.Threading.Timer` requires a void callback.
149+
// Catch all exceptions in it: any exceptions unhandled by the method might lead to the process crash
153150
private async void HeartbeatWriteTimerCallback(object? state)
154151
{
155-
if (_heartbeatWriteTimer is null)
156-
{
157-
return;
158-
}
159-
160152
try
161153
{
154+
if (_heartbeatWriteTimer is null)
155+
{
156+
return;
157+
}
158+
162159
if (false == _closed)
163160
{
164161
await WriteAsync(Client.Impl.Framing.Heartbeat.GetHeartbeatFrame(), _mainLoopCts.Token)

0 commit comments

Comments
 (0)