Update December 2019 With ASP.NET Core 3.1 now supporting background tasks using Microsoft.NET.Sdk.Worker this might not be what you need as it's excellent and works really well.
However as original project has been archived, and is stale, this is a new fork with some improvements.
If this is used in production environments, be aware the test coverage isn't where it needs to be, should you run into a problem please raise an issue
CloudCraic.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())
.
CloudCraic.Hosting.BackgroundQueue uses IHostedService and works with any .NET Core 2.0 IWebHost i.e. a server that supports ASP.NET Core.
CloudCraic.Hosting.BackgroundQueue also works with .NET Core's 2.1 lighter-weight IHost - i.e. just services no ASP.NET Core, ideal for microservices.
PM> Install-Package CloudCraic.Hosting.BackgroundQueue
In your ASP.NET Core Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddBackgroundQueue(maxConcurrentCount:1, millisecondsToWaitBeforePickingUpTask:1000,
onException:exception =>
{
});
}
This setups CloudCraic.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.
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();
}
CloudCraic.Hosting.BackgroundQueue uses a ConcurrentQueue and interlocked operations so is completely thread safe, just watch out for Access to Modified Closure issues.
CloudCraic.Hosting.BackgroundQueue is inspired by and gives credit to: