Skip to content

Commit 1f83050

Browse files
Avoid UnobservedTaskExceptions when getting an error in server to client streaming (dotnet#46198)
1 parent a67b751 commit 1f83050

File tree

2 files changed

+15
-6
lines changed

2 files changed

+15
-6
lines changed

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

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -611,13 +611,22 @@ public virtual IAsyncEnumerable<TResult> StreamAsyncCore<TResult>(string methodN
611611
private async IAsyncEnumerable<T> CastIAsyncEnumerable<T>(string methodName, object?[] args, CancellationTokenSource cts)
612612
{
613613
var reader = await StreamAsChannelCoreAsync(methodName, typeof(T), args, cts.Token).ConfigureAwait(false);
614-
while (await reader.WaitToReadAsync(cts.Token).ConfigureAwait(false))
614+
615+
try
615616
{
616-
while (reader.TryRead(out var item))
617+
while (await reader.WaitToReadAsync(cts.Token).ConfigureAwait(false))
617618
{
618-
yield return (T)item!;
619+
while (reader.TryRead(out var item))
620+
{
621+
yield return (T)item!;
622+
}
619623
}
620624
}
625+
finally
626+
{
627+
// Needed to avoid UnobservedTaskExceptions
628+
_ = reader.Completion.Exception;
629+
}
621630
}
622631

623632
private async Task<ChannelReader<object?>> StreamAsChannelCoreAsyncCore(string methodName, Type returnType, object?[] args, CancellationToken cancellationToken)

src/SignalR/clients/csharp/Client.Core/src/HubConnectionExtensions.StreamAsChannelAsync.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -302,9 +302,6 @@ private static async Task RunChannel<TResult>(ChannelReader<object?> inputChanne
302302
}
303303
}
304304
}
305-
306-
// Manifest any errors in the completion task
307-
await inputChannel.Completion.ConfigureAwait(false);
308305
}
309306
catch (Exception ex)
310307
{
@@ -314,6 +311,9 @@ private static async Task RunChannel<TResult>(ChannelReader<object?> inputChanne
314311
{
315312
// This will safely no-op if the catch block above ran.
316313
outputChannel.Writer.TryComplete();
314+
315+
// Needed to avoid UnobservedTaskExceptions
316+
_ = inputChannel.Completion.Exception;
317317
}
318318
}
319319
}

0 commit comments

Comments
 (0)