Skip to content

Commit 71fb082

Browse files
Avoid more UnobservedTaskExceptions in SignalR .NET client (#46781)
1 parent e1a063a commit 71fb082

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

src/SignalR/clients/csharp/Client.Core/src/HubConnection.Log.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -322,5 +322,8 @@ public static void ErrorHandshakeTimedOut(ILogger logger, TimeSpan handshakeTime
322322

323323
[LoggerMessage(88, LogLevel.Warning, "Error returning result for invocation '{InvocationId}' for method '{Target}' because the underlying connection is closed.", EventName = "ErrorSendingInvocationResult")]
324324
public static partial void ErrorSendingInvocationResult(ILogger logger, string invocationId, string target, Exception exception);
325+
326+
[LoggerMessage(89, LogLevel.Trace, "Error sending Completion message for stream '{StreamId}'.", EventName = "ErrorSendingStreamCompletion")]
327+
public static partial void ErrorSendingStreamCompletion(ILogger logger, string streamId, Exception exception);
325328
}
326329
}

src/SignalR/clients/csharp/Client.Core/src/HubConnection.cs

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -641,14 +641,17 @@ async Task OnStreamCanceled(InvocationRequest irq)
641641
{
642642
Log.SendingCancellation(_logger, irq.InvocationId);
643643

644-
// Fire and forget, if it fails that means we aren't connected anymore.
645-
_ = SendHubMessage(_state.CurrentConnectionStateUnsynchronized, new CancelInvocationMessage(irq.InvocationId), irq.CancellationToken);
644+
await SendHubMessage(_state.CurrentConnectionStateUnsynchronized, new CancelInvocationMessage(irq.InvocationId), irq.CancellationToken).ConfigureAwait(false);
646645
}
647646
else
648647
{
649648
Log.UnableToSendCancellation(_logger, irq.InvocationId);
650649
}
651650
}
651+
catch
652+
{
653+
// Connection closed while trying to cancel a stream. This is fine to ignore.
654+
}
652655
finally
653656
{
654657
_state.ReleaseConnectionLock();
@@ -849,6 +852,10 @@ private async Task CommonStreaming(ConnectionState connectionState, string strea
849852
Log.CompletingStreamNotSent(_logger, streamId);
850853
}
851854
}
855+
catch (Exception ex)
856+
{
857+
Log.ErrorSendingStreamCompletion(_logger, streamId, ex);
858+
}
852859
finally
853860
{
854861
_state.ReleaseConnectionLock();
@@ -1996,6 +2003,10 @@ internal async Task RunTimerActions()
19962003
await _hubConnection.SendHubMessage(this, PingMessage.Instance).ConfigureAwait(false);
19972004
}
19982005
}
2006+
catch
2007+
{
2008+
// The exception from send should be seen elsewhere in the client. We'll ignore it here.
2009+
}
19992010
finally
20002011
{
20012012
_hubConnection._state.ReleaseConnectionLock();

0 commit comments

Comments
 (0)