Let’s Learn Blazor: Background Service Communication with Blazor via SignalR

Let your ASP.NET Core Background Service communicate with your Blazor app via SignalR

Christopher Laine
IT Dead Inside
Published in
6 min readDec 14, 2022

--

This is one of several articles on Blazor I’ll be writing, all so engineers can get familiar with the capabilities and tricks of this burgeoning and exciting web technology

I was in a conundrum. I needed to process data outside of my Blazor server app’s main thread. I needed a long-running task which would handle a synchronisation process behind the scenes.

No big whoop, right? Just use the BackgroundService as a Hosted Service in the app and background processing is easy as could be.

//From my Program.cs
builder.Services.AddHostedService<MyBackgroundService>();

Then it was just a matter of constructing a simple class which inherits from BackgroundService and away we go.

public class MyBackgroundService : BackgroundService
{
//...etc

The problem for me was, I wanted the Background Service’s activity to appear inside my Blazor Server app as it was running.

Different Threads, Different Worlds

If you don’t know, this is harder than it sounds. The BackgrounService is running on the same app as the Blazor Server pages, sure, but they might as well be on two different worlds.

In a way, they are. The BackgroundService is running on a totally different asynchronous thread. It is in no way attached to HTTP (beyond being able to make HTTP calls). This is, of course, by design. A BackgroundService is meant to be running in isolation from the web server / pages so that it can do its job without fear of either of them interrupting the other. There is no simple way in an ASP.NET Core or Blazor Server App to allow that background thread to communicate with the Blazor App which is running above it.

Well, actually, I take that back. There is a way, and it’s actually quite simple.

SignalR to the Rescue

After a lot of googling on your behalf (you’re welcome), I found just what I was after. The most convenient mechanisms to do things are often the simplest ones, and in this case, the simplest solution is SignalR.

--

--