Skip to content

DalSoft/DalSoft.Hosting.BackgroundQueue

Repository files navigation

If you find this repo / package useful all I ask is you please star it.

Update August 2021 Although Microsoft.NET.Sdk.Worker works well, you end up with a lot of bolierplate code and have to solve things like exception handling and concurrency. MS are leaving it up to the end user to decide how to implement (which makes sense rather than trying to implement every scenario). For me I need something simple akin to HostingEnvironment.QueueBackgroundWorkItem, so I will continue to support and improve this package.

DalSoft.Hosting.BackgroundQueue

This is used in production environments, however the test coverage isn't where it needs to be, should you run into a problem please raise an issue

DalSoft.Hosting.BackgroundQueue is a very lightweight .NET Core replacement for HostingEnvironment.QueueBackgroundWorkItem it has no extra dependancies!

For those of you that haven't used HostingEnvironment.QueueBackgroundWorkItem it was a simple way in .NET 4.5.2 to safely run a background task on a webhost, for example sending an email when a user registers.

Yes there are loads of good options (hangfire, Azure Web Jobs/Functions) for doing this, but nothing in ASP.NET Core to replace the simplicity of the classic one liner HostingEnvironment.QueueBackgroundWorkItem(cancellationToken => DoWork()).

Supported Platforms

DalSoft.Hosting.BackgroundQueue uses IHostedService and works with any .NET Core 2.0 IWebHost i.e. a server that supports ASP.NET Core.

DalSoft.Hosting.BackgroundQueue also works with .NET Core's 2.1 lighter-weight IHost - i.e. just services no ASP.NET Core, ideal for microservices.

Getting Started

PM> Install-Package DalSoft.Hosting.BackgroundQueue

In your ASP.NET Core Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
   services.AddBackgroundQueue(maxConcurrentCount:1, millisecondsToWaitBeforePickingUpTask:1000, 
      onException:exception =>
      {
                   
      });
}

This setups DalSoft.Hosting.BackgroundQueue using .NET Core's DI container. If your using a different DI container you need to register BackgroundQueue and BackgroundQueueService as singletons.

maxConcurrentCount (optional) maxConcurrentCount is the number of Tasks allowed to run in the background concurrently. maxConcurrentCount defaults to 1.

millisecondsToWaitBeforePickingUpTask (optional) If the number of background Tasks exceeds the maxConcurrentCount then millisecondsToWaitBeforePickingUpTask is used to delay picking up Tasks until the current Task is completed. millisecondsToWaitBeforePickingUpTask defaults to 1000, setting millisecondsToWaitBeforePickingUpTask lower than 500 throws an exception.

onException (required) You are running tasks in the background on a different thread you need to know when an exception occurred. This is done using the Action<Exception> passed to onException. onException is called any time a Task throws an exception.

As you would expect exceptions only affect the Task causing the exception, all other Tasks are processed as normal.

Queuing a Background Task

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, cancellationToken);
   });

   return Ok();
}

Thread Safety

DalSoft.Hosting.BackgroundQueue uses a ConcurrentQueue and interlocked operations so is completely thread safe, just watch out for Access to Modified Closure issues.

Standing on the Shoulders of Giants

DalSoft.Hosting.BackgroundQueue is inspired by and gives credit to:

Releases

No releases published

Packages

No packages published

Languages