LESSON 8 OF 14

8. Long-Running Operations and Real-Time Progress Tracking

Learn how to monitor long-running file and report operations with SignalR, publish progress, support cancellation, and handle interrupted connections.

45 dk 54

Introduction

Processing a file, generating a large report, or importing a batch of records can take longer than a normal request. If users only see a blank waiting screen, they cannot tell whether the application is still working. A better design gives the operation an operationId, publishes progress through SignalR, and clearly reports when the operation starts, completes, is cancelled, or fails.

In this lesson, we will build a report-generation scenario. The client will invoke a hub method to start the operation, while a background worker performs the work and publishes OperationStarted, ProgressChanged, OperationCompleted, OperationCancelled, and OperationFailed events. We will also validate progress values, support automatic reconnection, and explain why a cancellation request may not stop an operation immediately.

Designing the operation lifecycle

A long-running operation should have an explicit lifecycle:

  1. The client requests a new operation.
  2. The server validates the request and creates a unique operationId.
  3. The server reports that the operation has started.
  4. A background worker publishes progress at controlled intervals.
  5. The operation completes, is cancelled, or ends with an error.

Progress should be calculated by the server because the server owns the actual work. Never trust a percentage supplied by the browser as the source of truth. Values should remain between 0 and 100 and should normally not move backwards.

Shared contracts

Start with contracts shared by the hub and the TypeScript client:

public record OperationStarted(string OperationId, string Name);
public record ProgressChanged(string OperationId, int Percent, string Message);
public record OperationCompleted(string OperationId, string Result);
public record OperationCancelled(string OperationId);
public record OperationFailed(string OperationId, string Error);

The equivalent TypeScript types can be defined as follows:

type OperationStarted = {
  operationId: string;
  name: string;
};

type ProgressChanged = {
  operationId: string;
  percent: number;
  message: string;
};

Starting work through a hub

The hub method should not perform the entire long-running operation. Keeping the invocation open while the job runs can cause timeouts, unnecessary connection pressure, and poor error handling. A better approach is to validate the request and place the job on a queue.

public interface IOperationQueue
{
    ValueTask QueueAsync(string operationId, CancellationToken cancellationToken);
}

public sealed class ReportHub : Hub
{
    private readonly IOperationQueue _queue;
    private readonly IOperationRegistry _operationRegistry;

    public ReportHub(
        IOperationQueue queue,
        IOperationRegistry operationRegistry)
    {
        _queue = queue;
        _operationRegistry = operationRegistry;
    }

    public async Task<string> StartReportAsync(string reportName)
    {
        if (string.IsNullOrWhiteSpace(reportName))
            throw new HubException("Report name is required.");

        var operationId = Guid.NewGuid().ToString("N");
        await _queue.QueueAsync(operationId, Context.ConnectionAborted);

        await Clients.Caller.SendAsync(
            "OperationStarted",
            new OperationStarted(operationId, reportName));

        return operationId;
    }

    public Task CancelReportAsync(string operationId)
    {
        return _operationRegistry.CancelAsync(operationId);
    }
}

The registry represents the cancellation manager used by the rest of the example. An in-memory implementation can be acceptable for a simple single-server application. In a multi-server deployment, use a shared store or job system and make sure cancellation commands can reach the server executing the operation.

Publishing progress from a BackgroundService

A background service consumes queued work and sends messages through a typed or untyped IHubContext<ReportHub>. Do not store a Hub instance for later use. Hub instances are associated with individual invocations; the hub context is the appropriate abstraction for sending messages from services.

public sealed class ReportWorker : BackgroundService
{
    private readonly IHubContext<ReportHub> _hub;
    private readonly IOperationQueue _queue;
    private readonly IOperationRegistry _registry;
    private readonly ILogger<ReportWorker> _logger;

    public ReportWorker(
        IHubContext<ReportHub> hub,
        IOperationQueue queue,
        IOperationRegistry registry,
        ILogger<ReportWorker> logger)
    {
        _hub = hub;
        _queue = queue;
        _registry = registry;
        _logger = logger;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        await foreach (var operationId in _queue.ReadAllAsync(stoppingToken))
        {
            try
            {
                using var operationCts =
                    CancellationTokenSource.CreateLinkedTokenSource(stoppingToken);
                _registry.Attach(operationId, operationCts);

                for (var percent = 0; percent <= 100; percent += 10)
                {
                    operationCts.Token.ThrowIfCancellationRequested();
                    await Task.Delay(300, operationCts.Token);

                    var safePercent = Math.Clamp(percent, 0, 100);
                    await _hub.Clients.All.SendAsync(
                        "ProgressChanged",
                        new ProgressChanged(operationId, safePercent,
                            $"{safePercent}% complete"),
                        stoppingToken);
                }

                await _hub.Clients.All.SendAsync(
                    "OperationCompleted",
                    new OperationCompleted(operationId, "Report is ready"),
                    stoppingToken);
            }
            catch (OperationCanceledException)
            {
                await _hub.Clients.All.SendAsync(
                    "OperationCancelled",
                    new OperationCancelled(operationId),
                    CancellationToken.None);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Operation failed: {OperationId}", operationId);
                await _hub.Clients.All.SendAsync(
                    "OperationFailed",
                    new OperationFailed(operationId, "The operation could not be completed"),
                    CancellationToken.None);
            }
            finally
            {
                _registry.Detach(operationId);
            }
        }
    }
}

In a real application, replace Clients.All with a narrower audience. Store the initiating user identifier with the operation and use Clients.User(userId), or add the initiating connection to a dedicated group. A report status should not accidentally be visible to every connected user.

Managing state in the TypeScript client

Register event handlers before starting the connection. Keep the status and progress for each operation separately so that multiple operations can be displayed at the same time.

const operations = new Map<string, {
  status: 'running' | 'completed' | 'cancelled' | 'failed';
  percent: number;
  message: string;
}>();

connection.on('OperationStarted', (event: OperationStarted) => {
  operations.set(event.operationId, {
    status: 'running',
    percent: 0,
    message: 'Operation started'
  });
  renderOperation(event.operationId);
});

connection.on('ProgressChanged', (event: ProgressChanged) => {
  const operation = operations.get(event.operationId);
  if (!operation) return;

  const percent = Math.max(0, Math.min(100, event.percent));
  operation.percent = Math.max(operation.percent, percent);
  operation.message = event.message;
  renderOperation(event.operationId);
});

connection.on('OperationCompleted', event => {
  const operation = operations.get(event.operationId);
  if (!operation) return;
  operation.status = 'completed';
  operation.percent = 100;
  operation.message = event.result;
  renderOperation(event.operationId);
});

connection.on('OperationCancelled', event => {
  const operation = operations.get(event.operationId);
  if (!operation) return;
  operation.status = 'cancelled';
  operation.message = 'Cancelled';
  renderOperation(event.operationId);
});

connection.on('OperationFailed', event => {
  const operation = operations.get(event.operationId);
  if (!operation) return;
  operation.status = 'failed';
  operation.message = event.error;
  renderOperation(event.operationId);
});

The renderOperation function can update the progress bar value, status text, and cancellation button. Display the percentage as text as well as visually so the status remains understandable to assistive technologies.

Handling interrupted connections

Automatic reconnect must be enabled explicitly in the JavaScript client:

const connection = new signalR.HubConnectionBuilder()
  .withUrl('/hubs/report')
  .withAutomaticReconnect([0, 2000, 10000, 30000])
  .build();

connection.onreconnecting(() => {
  setConnectionState('Reconnecting');
});

connection.onreconnected(() => {
  setConnectionState('Connected');
  refreshActiveOperations();
});

connection.onclose(() => {
  setConnectionState('Disconnected');
});

Successful reconnection does not replay events that were published while the client was offline. Therefore, call an HTTP endpoint or a dedicated status method such as GetOperationStatus after reconnection. SignalR events are useful for live updates, but a persisted operation record should remain the source of truth.

Designing cancellation safely

The client can request cancellation as follows:

async function cancelOperation(operationId: string) {
  try {
    await connection.invoke('CancelReportAsync', operationId);
  } catch (error) {
    showError('The cancellation request could not be sent.');
  }
}

A cancellation request does not guarantee that the operation stops immediately. The job may be waiting on an external service, executing a non-interruptible database command, or completing an atomic step. Show a temporary “cancellation requested” state instead of immediately displaying “cancelled.” The final state should be set only after the server publishes OperationCancelled. If a particular operation cannot be cancelled, report that condition explicitly.

Common mistakes

  • Awaiting the entire job inside the hub method: Use the hub for validation and queueing, not for the complete long-running workflow.
  • Trusting every progress value: Clamp values on the server and validate them defensively on the client.
  • Treating a connection ID as a permanent user identity: Connection IDs may change after reconnection. Associate operations with a user or operation ID.
  • Keeping state only in the browser: Refreshing the page or losing the connection will remove the state.
  • Ignoring cleanup after cancellation: Release temporary files, registrations, locks, and registry entries in a finally block.
  • Confusing message delivery with job success: Failure to send a SignalR message is not necessarily the same as failure of the underlying operation.

Practice exercise

  1. Create a ReportHub and a BackgroundService.
  2. Publish progress in increments of five every 500 milliseconds.
  3. Build a TypeScript progress bar and status message.
  4. Add a cancellation button backed by a CancellationTokenSource.
  5. Temporarily disable the network in the browser and refresh the operation state after reconnection.
  6. Test invalid values such as -10, 120, and a value lower than the previous percentage.

Conclusion

A reliable SignalR progress system is more than a percentage label. It requires a queue or background worker, an operation identifier, a trustworthy state model, clear cancellation semantics, failure reporting, and state recovery after reconnection. SignalR delivers live events, while a persistent operation record provides durable truth. With these responsibilities separated, file processing and report generation become easier to understand for users and more resilient in production.

Sources