Introduction
A task dashboard is an excellent example for real-time applications. When one user creates a task, another user completes it, or a task is deleted, everyone viewing the dashboard should see the change without refreshing the page. In this lesson, we will turn task operations into SignalR events and update the dashboard with a TypeScript client.
Tasks will be persisted through a Web API or application service, while the SignalR Hub will notify connected clients about successful changes. The Hub will not become the central location for database logic; business rules remain in the service layer. This separation improves testability and makes it easier to add a background service or Redis backplane later.
We will compare two user interface strategies: optimistic UI, which displays a local change before the server responds, and server-confirmed UI, which updates the interface only after the server successfully completes the operation. We will also test concurrent edits, out-of-order events, and missing event handlers.
1. Design the event contract
Begin by defining the data model and event names shared by the server and client. Clear and consistent event names reduce accidental mismatches on the client. This lesson uses the following events:
| Event | When is it published? | Client behavior |
|---|---|---|
TaskCreated | When a new task is created | Add the task to the list |
TaskUpdated | When the title or description changes | Update the existing task |
TaskStatusChanged | When the task status changes | Refresh the status and visual state |
TaskDeleted | When a task is deleted | Remove the task from the list |
Include a Version property to help detect concurrent changes. In a production system, this can map to a database concurrency token or a SQL Server rowversion value.
export type TaskStatus = "Todo" | "InProgress" | "Done";
export interface TaskItem {
id: string;
title: string;
description?: string;
status: TaskStatus;
version: number;
updatedAtUtc: string;
}The server-side DTOs can represent the same concepts:
public sealed record TaskItemDto(
Guid Id,
string Title,
string? Description,
string Status,
int Version,
DateTime UpdatedAtUtc);
public sealed record TaskCreatedEvent(TaskItemDto Task);
public sealed record TaskUpdatedEvent(TaskItemDto Task);
public sealed record TaskStatusChangedEvent(TaskItemDto Task);
public sealed record TaskDeletedEvent(Guid TaskId, int Version);2. Create the Hub and service layer
The Hub receives a client call, delegates it to the application service, and publishes an event after the operation succeeds. Putting database logic directly in Hub methods may be convenient in a small demo, but it mixes responsibilities as the application grows.
public interface ITaskService
{
Task<TaskItemDto> CreateAsync(string title, string? description);
Task<TaskItemDto> UpdateAsync(Guid id, string title, string? description, int expectedVersion);
Task<TaskItemDto> ChangeStatusAsync(Guid id, string status, int expectedVersion);
Task DeleteAsync(Guid id, int expectedVersion);
}
public sealed class TaskHub(ITaskService tasks) : Hub
{
public async Task<TaskItemDto> CreateTask(string title, string? description)
{
var task = await tasks.CreateAsync(title, description);
await Clients.All.SendAsync("TaskCreated", new TaskCreatedEvent(task));
return task;
}
public async Task<TaskItemDto> UpdateTask(
Guid id, string title, string? description, int expectedVersion)
{
var task = await tasks.UpdateAsync(id, title, description, expectedVersion);
await Clients.All.SendAsync("TaskUpdated", new TaskUpdatedEvent(task));
return task;
}
public async Task<TaskItemDto> ChangeTaskStatus(
Guid id, string status, int expectedVersion)
{
var task = await tasks.ChangeStatusAsync(id, status, expectedVersion);
await Clients.All.SendAsync("TaskStatusChanged", new TaskStatusChangedEvent(task));
return task;
}
public async Task DeleteTask(Guid id, int expectedVersion)
{
await tasks.DeleteAsync(id, expectedVersion);
await Clients.All.SendAsync("TaskDeleted", new TaskDeletedEvent(id, expectedVersion));
}
}Clients.All broadcasts to every connected client. If tasks belong to a workspace or tenant, use Clients.Group(workspaceId) instead. This prevents one customer’s changes from appearing in another customer’s dashboard.
Register the Hub and service in the application startup configuration:
builder.Services.AddSignalR();
builder.Services.AddScoped<ITaskService, TaskService>();
var app = builder.Build();
app.MapHub<TaskHub>("/hubs/tasks");3. Prepare the TypeScript client
Register client event handlers before calling start. This is a useful practice because it ensures the handlers exist before any messages can arrive after the connection is established.
import * as signalR from "@microsoft/signalr";
import type { TaskItem } from "./models";
const connection = new signalR.HubConnectionBuilder()
.withUrl("/hubs/tasks")
.withAutomaticReconnect()
.build();
const tasks = new Map<string, TaskItem>();
connection.on("TaskCreated", (event: { task: TaskItem }) => {
tasks.set(event.task.id, event.task);
renderTasks();
});
connection.on("TaskUpdated", (event: { task: TaskItem }) => {
applyServerTask(event.task);
});
connection.on("TaskStatusChanged", (event: { task: TaskItem }) => {
applyServerTask(event.task);
});
connection.on("TaskDeleted", (event: { taskId: string }) => {
tasks.delete(event.taskId);
renderTasks();
});
function applyServerTask(task: TaskItem): void {
const current = tasks.get(task.id);
if (!current || task.version >= current.version) {
tasks.set(task.id, task);
renderTasks();
}
}The version comparison prevents an older event from overwriting newer client state when network delays cause messages to arrive out of order. This does not replace server-side concurrency validation; it only protects the client’s local view.
4. Invoke task operations from the client
Use invoke when the client needs to wait for the Hub method to finish and handle its result or error. Since the server also publishes an event, all clients can update through the same event handlers instead of duplicating rendering logic.
export async function createTask(title: string, description?: string) {
await connection.invoke("CreateTask", title, description);
}
export async function updateTask(
task: TaskItem,
title: string,
description?: string) {
await connection.invoke(
"UpdateTask",
task.id,
title,
description,
task.version);
}
export async function changeStatus(task: TaskItem, status: TaskStatus) {
await connection.invoke(
"ChangeTaskStatus",
task.id,
status,
task.version);
}
export async function deleteTask(task: TaskItem) {
await connection.invoke("DeleteTask", task.id, task.version);
}When an operation fails, show a meaningful message. For example, the service can reject the request when the expected version differs from the database version. The client can then reload the task and tell the user that another person changed it.
5. Comparing optimistic and server-confirmed UI
Server-confirmed approach
With a server-confirmed UI, disable the status control while the request is in progress. If invoke succeeds, the event updates the dashboard. If it fails, the current display remains unchanged.
async function setStatusConfirmed(task: TaskItem, status: TaskStatus) {
setTaskBusy(task.id, true);
try {
await connection.invoke(
"ChangeTaskStatus",
task.id,
status,
task.version);
} catch (error) {
showError("The status could not be changed. Try again.");
console.error(error);
} finally {
setTaskBusy(task.id, false);
}
}This approach makes data correctness easier to reason about. Its disadvantage is that the interface can feel slow when network latency is high.
Optimistic approach
An optimistic UI applies the change immediately and stores the previous value temporarily. If the server rejects the operation, the client rolls back to the previous state.
async function setStatusOptimistic(task: TaskItem, status: TaskStatus) {
const previous = { ...task };
tasks.set(task.id, { ...task, status });
renderTasks();
try {
await connection.invoke(
"ChangeTaskStatus",
task.id,
status,
task.version);
} catch (error) {
tasks.set(task.id, previous);
renderTasks();
showError("The change was not saved; the previous status was restored.");
console.error(error);
}
}Optimistic updates make the application feel responsive, but they become more complex when concurrent events arrive. The server-confirmed event should replace the temporary local state using the authoritative version. If several operations may be pending at once, use a client operation identifier or a small pending-operation queue.
6. Concurrent changes and race conditions
If two users update the same task using the same version, the first operation increments the version. The second operation sends an outdated expectedVersion and should be rejected. Otherwise, the last writer can silently overwrite another user’s work.
if (entity.Version != expectedVersion)
{
throw new TaskConcurrencyException(
"The task has a newer version.");
}
entity.Title = title;
entity.Description = description;
entity.Version++;
entity.UpdatedAtUtc = DateTime.UtcNow;Event order also matters on the client. For example, TaskUpdated may arrive before or after TaskStatusChanged. If both events contain the complete task representation, the client can decide by comparing versions. If events contain only changed fields, use field-level merging or reload the task from the server.
SignalR events are useful for updating the user interface, but receiving an event does not by itself prove that a persistent data operation succeeded. Validation and concurrency checks must remain on the server.
7. Reconnection and testing missing handlers
When automatic reconnect is enabled, the client can attempt to restore a connection after a temporary network failure. After reconnecting, the dashboard may have missed events. A safe strategy is to reload the current task list through HTTP in the onreconnected callback.
connection.onreconnecting(() => {
setConnectionState("Reconnecting...");
});
connection.onreconnected(async () => {
setConnectionState("Connected");
await reloadTasksFromApi();
});
connection.onclose(() => {
setConnectionState("Disconnected");
});Open two browser windows for testing. Create a task in one window and verify that it appears in the other. Then edit the same task quickly in both windows. Confirm that one request is rejected with a concurrency error and that the client reloads the current version.
To test a missing event handler, temporarily keep the server-side TaskStatusChanged broadcast enabled but remove the corresponding connection.on registration. The server operation will succeed, but the dashboard will not change. This demonstrates why event contracts should be covered by integration tests.
Practice exercise
- Add the
TaskItemmodel and aVersionproperty to the existing project. - Create the
CreateTask,UpdateTask,ChangeTaskStatus, andDeleteTaskHub methods. - Publish the four SignalR events and register their TypeScript handlers.
- Implement a server-confirmed status change, then implement an optimistic version.
- Use two clients to modify the same task and verify the concurrency behavior.
- Intentionally remove one event handler and observe why the dashboard becomes stale.
Conclusion
In this lesson, we transformed a task dashboard from a one-time HTTP response into a real-time interface driven by events. We defined an event contract, separated the Hub from the application service, and used a TypeScript client to create, update, change, and delete tasks. Optimistic UI provides a low-latency experience, while server-confirmed UI makes authoritative state easier to maintain.
In production applications, version checks, reconnection recovery, correct audience targeting, and tests for every event handler are essential. In later lessons, these event flows can be combined with authentication, authorization, and more advanced connection management.