Skip to content

Instantly share code, notes, and snippets.

@henningjensen
Created February 4, 2022 09:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save henningjensen/79755f740cb706b600fa2778fead8628 to your computer and use it in GitHub Desktop.
Save henningjensen/79755f740cb706b600fa2778fead8628 to your computer and use it in GitHub Desktop.
dotnet api controller run long running job - populate cache example
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
namespace MyNamespace.Controllers;
[Route("/api/cache")]
[ApiController]
public class CacheController : ControllerBase
{
[HttpGet("populate-cache")]
public IActionResult PopulateCache([FromServices] IServiceScopeFactory serviceScopeFactory)
{
// Do not capture services injected into the controllers on background threads
// https://docs.microsoft.com/en-us/aspnet/core/performance/performance-best-practices?view=aspnetcore-3.1#do-not-capture-services-injected-into-the-controllers-on-background-threads
_ = Task.Run(async () =>
{
await Task.Delay(1000);
using (var scope = serviceScopeFactory.CreateScope())
{
var myCacheService = scope.ServiceProvider.GetRequiredService<MyCacheService>();
await myCacheService.BuildCache();
}
});
return Accepted();
}
}
public class MyCacheService
{
public async Task BuildCache()
{
// do long running stuff here
await Task.Delay(5000);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment