Created
February 4, 2022 09:08
-
-
Save henningjensen/79755f740cb706b600fa2778fead8628 to your computer and use it in GitHub Desktop.
dotnet api controller run long running job - populate cache example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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