Skip to content

Commit 213a4ab

Browse files
authored
Better Disconnect on Disposal (#268)
1 parent 3f151a2 commit 213a4ab

File tree

1 file changed

+7
-2
lines changed

1 file changed

+7
-2
lines changed

Source/HiveMQtt/Client/HiveMQClientUtil.cs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -175,14 +175,19 @@ protected virtual void Dispose(bool disposing)
175175
// and unmanaged resources.
176176
if (disposing)
177177
{
178-
if (this.Connection.State == Internal.ConnectState.Connected)
178+
if (this.Connection?.State == Internal.ConnectState.Connected)
179179
{
180180
Logger.Trace("HiveMQClient Dispose: Disconnecting connected client.");
181181
try
182182
{
183183
// Use Task.Run to handle the async disconnect without blocking
184+
// Use a reasonable timeout to avoid hanging indefinitely
184185
#pragma warning disable VSTHRD002 // Synchronous Wait in dispose pattern is intentional to ensure cleanup
185-
Task.Run(async () => await this.DisconnectAsync().ConfigureAwait(false)).Wait(5000);
186+
var disconnectTask = Task.Run(async () => await this.DisconnectAsync().ConfigureAwait(false));
187+
if (!disconnectTask.Wait(5000))
188+
{
189+
Logger.Warn("Disconnect operation timed out during dispose");
190+
}
186191
#pragma warning restore VSTHRD002
187192
}
188193
catch (Exception ex)

0 commit comments

Comments
 (0)