Skip to content

SignalR C# Client StartAsync() CancellationToken not respected #39626

@Kolky

Description

@Kolky

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

Similar to #10059. I have a Client application (WPF .NET6) that uses the DI-framework which hosts a service on the background that connects to a SignalR hub. The cancellationtoken seems to not be respected and never finishes my task and thus blocks my application from exiting.

Expected Behavior

I would expect that I receive a TaskCanceledException.

Steps To Reproduce

To reproduce this you should have your SignalR server turned off (I don't think you even need a server!). In the below example the "await" start-task never finishes.

Example client code:

    internal class ServerProxy : IHostedService
    {
        private readonly HubConnection _connection;
        private readonly CancellationTokenSource _cts = new();
        private Task _startTask;

        public ServerProxy(IConfiguration configuration)
        {
            _connection = new HubConnectionBuilder()
                .WithUrl($"{configuration.GetValue<string>("ServerBaseAddress")}/messages")
                .WithAutomaticReconnect()
                .Build();
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            _startTask = _connection.StartAsync(_cts.Token);
            return Task.CompletedTask;
        }

        public async Task StopAsync(CancellationToken cancellationToken)
        {
            if (_startTask != null && !_startTask.IsCompleted)
            {
                _cts.Cancel();
                try
                {
                    await _startTask;
                }
                catch (TaskCanceledException)
                {
                    // Do nothing
                }
            }

            if (_connection.State == HubConnectionState.Connected)
            {
                await _connection.StopAsync();
                await _connection.DisposeAsync();
            }
        }
    }

Exceptions (if any)

n/a

.NET Version

6.0.100

Anything else?

Using the Package "Microsoft.AspNetCore.SignalR.Client" Version="6.0.1".

Metadata

Metadata

Assignees

Labels

area-signalrIncludes: SignalR clients and servers

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions