Alternative solution to HostingEnvironment.QueueBackgroundWorkItem in .NET Core

后端 未结 6 1857
栀梦
栀梦 2020-12-23 11:04

We are working with .NET Core Web Api, and looking for a lightweight solution to log requests with variable intensity into database, but don\'t want client\'s to wait for th

6条回答
  •  旧巷少年郎
    2020-12-23 11:43

    Update December 2019: ASP.NET Core 3.0 supports an easy way to implement background tasks using Microsoft.NET.Sdk.Worker. It's excellent and works really well.

    As @axelheer mentioned IHostedService is the way to go in .NET Core 2.0 and above.

    I needed a lightweight like for like ASP.NET Core replacement for HostingEnvironment.QueueBackgroundWorkItem, so I wrote DalSoft.Hosting.BackgroundQueue which uses.NET Core's 2.0 IHostedService.

    PM> Install-Package DalSoft.Hosting.BackgroundQueue

    In your ASP.NET Core Startup.cs:

    public void ConfigureServices(IServiceCollection services)
    {
       services.AddBackgroundQueue(onException:exception =>
       {
    
       });
    }
    

    To queue a background Task just add BackgroundQueue to your controller's constructor and call Enqueue.

    public EmailController(BackgroundQueue backgroundQueue)
    {
       _backgroundQueue = backgroundQueue;
    }
    
    [HttpPost, Route("/")]
    public IActionResult SendEmail([FromBody]emailRequest)
    {
       _backgroundQueue.Enqueue(async cancellationToken =>
       {
          await _smtp.SendMailAsync(emailRequest.From, emailRequest.To, request.Body);
       });
    
       return Ok();
    }
    

提交回复
热议问题