From eb9f6af786ddd0215fccf48185ec94554604ebc0 Mon Sep 17 00:00:00 2001 From: Jason Kamleh Date: Mon, 13 Nov 2023 15:14:42 +1100 Subject: [PATCH] Fix BasicRabbitService disconnection - Disposing channel and connection objects is not enough. See https://www.rabbitmq.com/dotnet-api-guide.html#disconnecting - It's generally not a good practice to lock on 'this' because code from other classes can potentially acquire a lock on the same object leading to deadlocks. Refactored to new object like what is used elsewhere in this project --- SimpleRabbit.NetCore/Service/BasicRabbitService.cs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/SimpleRabbit.NetCore/Service/BasicRabbitService.cs b/SimpleRabbit.NetCore/Service/BasicRabbitService.cs index 5a593d2..8e90b7d 100644 --- a/SimpleRabbit.NetCore/Service/BasicRabbitService.cs +++ b/SimpleRabbit.NetCore/Service/BasicRabbitService.cs @@ -15,6 +15,7 @@ public interface IBasicRabbitService : IDisposable public abstract class BasicRabbitService : IBasicRabbitService { + private readonly object _lock = new object(); private const ushort DefaultRequestedHeartBeat = 5; private const int DefaultNetworkRecoveryInterval = 10; @@ -79,7 +80,7 @@ protected BasicRabbitService(RabbitConfiguration config) public IBasicProperties GetBasicProperties() { - lock(this) + lock (_lock) { return Channel.CreateBasicProperties(); } @@ -87,7 +88,7 @@ public IBasicProperties GetBasicProperties() public void ClearConnection() { - lock (this) + lock (_lock) { if (_disposed) { @@ -95,11 +96,13 @@ public void ClearConnection() } try { + _channel?.Close(); _channel?.Dispose(); _channel = null; } finally { + _connection?.Close(); _connection?.Dispose(); _connection = null; } @@ -109,7 +112,7 @@ public void ClearConnection() public void Close() { - lock (this) + lock (_lock) { if (_disposed) {