Monday, September 3, 2018

SignalR on a background thread in .Net Core


Recently I've been working on a project utilizing SignalR.Core and .Net Core. I'm amazed how SignalR has stabilized since its beginning.

While I intend to build some posts detailing my recent experience, this one is to show a not very well documented thing we can do with SignalR: how to send a message to the client from the hub on a background thread.

Solution

The solution is based on 3 simple steps:
  1. Inject IHubContext into your hub
  2. Span a background thread (or task)
  3. Send messages back to the clients using IHubContext

Let's take a look.

Step 1 - Inject IHubContext into your hub

private readonly IHubContext<ChatHub> _hubContext; public ChatHub(UserManager<MgmPlatUser> userManager, ApplicationDbContext context, IHubContext<ChatHub> hubContext) { this.userManager = userManager; this.context = context; this._hubContext = hubContext; // through this instance we access SignalR in a background tab }

Step 2 - Span a background thread (or task)

private void DoSomething(string id) { // do a bunch of stuff // .... // then, span a thread to rerun my command in the background new Thread(() => OnWaitEnded(m.Id)).Start(); }

Step 3 - Send messages back to the clients using IHubContext

private void OnWaitEnded(string id){ // wait X secs until my wait period ends if it makes sense.... while (m.ExpiresAt > DateTime.UtcNow){ var ttl = m.ExpiresAt.Subtract(DateTime.UtcNow).Milliseconds; Thread.Sleep( ttl ); } _hubContext.Clients.All.SendAsync("OnWaitEnded" , id, "our event waited"); // call clients using our IHubContext }

See Also

Why you should start using .Net Core
Package Management in .Net Core
Exporting Html to Pdf using only JavaScript
Importing CSVs with .Net Core and C#
Exporting a CSV generated in-memory in Asp.Net with C#
Building and Running Asp.Net Core apps on Linux
Asp.Net / Asp.Net Core: Generating views in the backend

For more posts on .Net Core, please click here.

References