Short running background task in .NET Core

Makla

I just discovered IHostedService and .NET Core 2.1 BackgroundService class. I think idea is awesome. Documentation.

All examples I found are used for long running tasks (until application die). But I need it for short time. Which is the correct way of doing it?

For example:
I want to execute a few queries (they will take approx. 10 seconds) after application starts. And only if in development mode. I do not want to delay application startup so IHostedService seems good approach. I can not use Task.Factory.StartNew, because I need dependency injection.

Currently I am doing like this:

public class UpdateTranslatesBackgroundService: BackgroundService
{
    private readonly MyService _service;

    public UpdateTranslatesBackgroundService(MyService service)
    {
        //MService injects DbContext, IConfiguration, IMemoryCache, ...
        this._service = service;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        await ...
    }
}

startup:

public static IServiceProvider Build(IServiceCollection services, ...)
{
    //.....
    if (hostingEnvironment.IsDevelopment())
        services.AddSingleton<IHostedService, UpdateTranslatesBackgroundService>();
    //.....
}

But this seems overkill. Is it? Register singleton (that means class exists while application lives). I don't need this. Just create class, run method, dispose class. All in background task.

Doug

There's no need to do any magic for this to work.

Simply:

  • Register the service you need to run in ConfigureServices
  • Resolve the instance you need in Configure and run it.
  • To avoid blocking, use Task.Run.

You must register the instance, or dependency injection won't work. That's unavoidable; if you need DI, then you have to do it.

Beyond that, it's trivial to do what you ask, like this:

public class Startup
{
  public Startup(IConfiguration configuration)
  {
    Configuration = configuration;
  }

  public IConfiguration Configuration { get; }

  // This method gets called by the runtime. Use this method to add services to the container.
  public void ConfigureServices(IServiceCollection services)
  {
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    services.AddTransient<MyTasks>(); // <--- This
  }

  // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  {
    if (env.IsDevelopment())
    {
      app.UseDeveloperExceptionPage();

      // Blocking
      app.ApplicationServices.GetRequiredService<MyTasks>().Execute();

      // Non-blocking
      Task.Run(() => { app.ApplicationServices.GetRequiredService<MyTasks>().Execute(); });
    }
    else
    {
      app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseMvc();
  }
}

public class MyTasks
{
  private readonly ILogger _logger;

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

  public void Execute()
  {
    _logger.LogInformation("Hello World");
  }
}

BackgroundService exists specifically for long running processes; if it's a once of, don't use it.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Asp.Net core long running/background task

Running background task on demand in asp.net core 3.x

Mysterious Behavior of .NET Core Background Task

Google Cloud Background Task with .Net Core

Swiftui Task not running in Background task

Tkinter Running Task In Background

Async Task not running in background?

Running a Task in the background (PCL)

Running a capistrano task in background

Running task / function in the background

Start Background Task using ASP.Net Core Middleware

User session in background task in ASP.NET Core

How can I manually cancel a .NET core IHostedService background task?

Execute a short background task in a rails controller

getting result in short running celery task (Django)

running asyncio task concurrently and in background

(iOS)Running download task in background

asp.net core 2 web api task run background task

ASP.Net Core Background Service with Task Queue, does it need a Task.Delay?

Launching a long-running background task - from ASP.NET or a scheduled job

Running an ECS Task on a Schedule With .NET

How to run multiple task in background service in .net core with different timer duration

How to create a background task in startup service in asp.net core 1.0 Web API?

Task.Run not running in background but on Dispatcher

How to use Rxjava for long running background task

Right way of running a root task/program at background

Android Studio: Background task running indefinitely

Background vs foreground task and running tasks in parallel

Running a task in background on jsf form submit