Checking the status of an IHostedService from another project?

866 Views Asked by At

I'm currently working on a project which processes files via a Hosted Service background task, persists those files to a DB, then show the user that data via a webpage. The webpage and the background task are in different .NET projects: the background task in a Web API and the webpage in a MVC App. The task runs every 5 minutes.

My goal is to be able to, from the MVC Controller, reach out to the Hosted Service and ask if the task is running or if it isn't. I'm unsure if there's something within Hosted Services that I'm missing or if a 3rd-party library is the answer. I'm also unsure if there's a direct, programmatic property way to do this or if it'll have to be some sort of messaging system. I've seen things like Rabbit and Hangfire in my research, but I'm not sure if that's necessary.

The following code is all from the Hosted Service project. Here is the code for the Document Processor

public class DocProcessor: IHostedService
{
    private readonly ILogger<DocProcessor> _logger;
    private readonly IWorker _worker;

    public DocProcessor(ILogger<DocProcessor> logger, IWorker worker)
    {
        _logger = logger;
        _worker = worker;
    }

    public async Task StartAsync(CancellationToken cancellationToken)
    {
        await _worker.DoWork(cancellationToken);
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("Stopping task.");
        return Task.CompletedTask;
    }
}

Here is the IWorker interface:

public interface IWorker
{
    Task DoWork(CancellationToken cancellationToken);
}

Here is the DocProcessorWorker:

public class DocProcessorWorker: IWorker
{
    private readonly ILogger<DocProcessorWorker> _logger;

    public DocProcessorWorker(ILogger<DocProcessorWorker> logger)
    {
        _logger = logger;
    }

    public async Task DoWork(CancellationToken cancellationToken)
    {
        while (!cancellationToken.IsCancellationRequested)
        {
            ... Work Being Done
            await Task.Delay(TimeSpan.FromMinutes(5), cancellationToken);
        }
    }
}

And the services portion of Program.cs:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHostedService<DocProcessor>();
builder.Services.AddSingleton<IWorker, DocProcessorWorker>();
...Other stuff...
var app = builder.Build();
0

There are 0 best solutions below