'(ASP.NET 6 + React) IHostedService is blocking React from loading data from the backend
I have and modular application which runs on an ASP.NET 6 Web API + React, made by the following template: https://docs.microsoft.com/en-us/visualstudio/javascript/tutorial-asp-net-core-with-react?view=vs-2022
Now, in my ASP.NET application I have an IHostedService that is running two tasks continuously, which looks like follows (code abbreviated for clarity)
IHostedService.cs
public async Task StartAsync(CancellationToken cancellationToken)
{
var task1 = Task1();
var task2 = Task2(cancellationToken);
await Task.WhenAll(task1, task2);
}
private async Task Task1(CancellationToken cancellationToken)
{
while (true)
{
//runs code continuously
}
}
private async Task Task2(CancellationToken cancellationToken)
{
while (true)
{
//runs code continuously
}
}
Since in ASP.NET 6 there's no more Startup.cs I added my HostedService to Program.cs like following:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddHostedService<MyHostedService>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
My backend including Task1 and Task2 from the IHostedService are running fine, however when my browser opens the ReactApp front-end it is stuck on loading since it's blocked by the IHostedService running continuous Tasks.
Now my question is, how can I prevent my IHostedService from blocking my React App from loading. Any help would be greatly appreciated!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

