├── src └── BackgroundTaskQueue │ ├── BackgroundQueue │ ├── ServiceCollectionExtensions.cs │ ├── Generic │ │ ├── ServiceCollectionExtensions.cs │ │ ├── Models │ │ │ ├── TicketBase.cs │ │ │ ├── BaseTicket.cs │ │ │ └── Ticket.cs │ │ ├── BackgroundResultQueueService.cs │ │ ├── BackgroundResultQueue.cs │ │ └── IBackgroundResultQueue.cs │ ├── Models │ │ ├── BaseTicket.cs │ │ └── Ticket.cs │ ├── IBackgroundTaskQueue.cs │ ├── BackgroundTaskQueue.cs │ ├── BackgroundQueue.csproj │ ├── BackgroundTaskQueueService.cs │ └── BackgroundQueue.xml │ └── BackgroundQueue.sln ├── LICENSE ├── README.md └── .gitignore /src/BackgroundTaskQueue/BackgroundQueue/ServiceCollectionExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | 3 | namespace BackgroundQueue 4 | { 5 | public static partial class ServiceCollectionExtensions 6 | { 7 | /// 8 | /// Adds the required BackgroundTaskQueue services. 9 | /// 10 | public static IServiceCollection AddBackgroundTaskQueue(this IServiceCollection services) => 11 | services 12 | .AddSingleton() 13 | .AddHostedService(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/BackgroundTaskQueue/BackgroundQueue/Generic/ServiceCollectionExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | 3 | namespace BackgroundQueue.Generic 4 | { 5 | public static partial class ServiceCollectionExtensions 6 | { 7 | /// 8 | /// Adds the required BackgroundResultQueue services. 9 | /// 10 | public static IServiceCollection AddBackgroundResultQueue( 11 | this IServiceCollection services 12 | ) => 13 | services 14 | .AddSingleton() 15 | .AddHostedService(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/BackgroundTaskQueue/BackgroundQueue/Models/BaseTicket.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | 5 | namespace BackgroundQueue.Models 6 | { 7 | internal class BaseTicket : Ticket 8 | { 9 | private readonly Func _task; 10 | private readonly Action _exception; 11 | 12 | internal BaseTicket(Func task, Action exception) 13 | { 14 | _task = task; 15 | _exception = exception; 16 | } 17 | 18 | public override Task ExecuteAsync(CancellationToken ct) => _task(ct); 19 | 20 | public override void OnException(Exception ex) => _exception(ex); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/BackgroundTaskQueue/BackgroundQueue/Generic/Models/TicketBase.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | 5 | namespace BackgroundQueue.Generic.Models 6 | { 7 | /// 8 | /// This class is only for internal use. 9 | /// 10 | public abstract class TicketBase 11 | { 12 | /// 13 | /// Gets called when the gets enqueued. 14 | /// 15 | public virtual void Enqueued() { } 16 | 17 | /// 18 | /// Gets called when the method errors out. 19 | /// 20 | public virtual void OnException(Exception ex) { } 21 | 22 | internal abstract Task ProccessAsync(CancellationToken ct); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/BackgroundTaskQueue/BackgroundQueue/Models/Ticket.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | 5 | namespace BackgroundQueue.Models 6 | { 7 | /// 8 | /// Inherit from this class, if you want to create a new Ticket, which should get enqueued in a BackgroundTaskQueue. 9 | /// 10 | public abstract class Ticket 11 | { 12 | /// 13 | /// Gets called when the gets enqueued. 14 | /// 15 | public virtual void Enqueued() { } 16 | 17 | /// 18 | /// Gets called when the method errors out. 19 | /// 20 | public virtual void OnException(Exception ex) { } 21 | 22 | /// 23 | /// Contains the core logic of the Ticket. 24 | /// 25 | public abstract Task ExecuteAsync(CancellationToken ct); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Twenty 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/BackgroundTaskQueue/BackgroundQueue.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.29411.138 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BackgroundQueue", "BackgroundQueue\BackgroundQueue.csproj", "{5864A1EB-DFEF-40A6-BDFE-4C8C536736DC}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {5864A1EB-DFEF-40A6-BDFE-4C8C536736DC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {5864A1EB-DFEF-40A6-BDFE-4C8C536736DC}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {5864A1EB-DFEF-40A6-BDFE-4C8C536736DC}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {5864A1EB-DFEF-40A6-BDFE-4C8C536736DC}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {8B58955E-8F70-4F4C-9E34-BC5DD1DCD43F} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /src/BackgroundTaskQueue/BackgroundQueue/Generic/Models/BaseTicket.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | 5 | namespace BackgroundQueue.Generic.Models 6 | { 7 | internal class BaseTicket : Ticket 8 | { 9 | private readonly Func _task; 10 | private readonly Action _exception; 11 | 12 | internal BaseTicket(Func task, Action exception) 13 | { 14 | _task = task; 15 | _exception = exception; 16 | } 17 | 18 | public override Task ExecuteAsync(CancellationToken ct) => _task(ct); 19 | 20 | public override void OnException(Exception ex) => _exception(ex); 21 | } 22 | 23 | internal class BaseTicket : Ticket 24 | { 25 | private readonly Func> _task; 26 | private readonly Action _exception; 27 | 28 | internal BaseTicket(Func> task, Action exception) 29 | { 30 | _task = task; 31 | _exception = exception; 32 | } 33 | 34 | public override Task ExecuteAsync(CancellationToken ct) => _task(ct); 35 | 36 | public override void OnException(Exception ex) => _exception(ex); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/BackgroundTaskQueue/BackgroundQueue/IBackgroundTaskQueue.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | using BackgroundQueue.Models; 5 | 6 | namespace BackgroundQueue 7 | { 8 | public interface IBackgroundTaskQueue : IDisposable 9 | { 10 | /// 11 | /// Adds a new to the Queue, which will get processed in a background thread. This method will return immediately. 12 | /// 13 | /// The Task which will get enqueued. 14 | void Enqueue(Func task); 15 | 16 | /// 17 | /// Adds a new to the Queue, which will get processed in a background thread. This method will return immediately. 18 | /// 19 | /// The Task which will get enqueued. 20 | /// A action which will get called, if the task fails. 21 | void Enqueue(Func task, Action exception); 22 | 23 | /// 24 | /// Adds a new to the Queue, which will get processed in a background thread. This method will return immediately. 25 | /// 26 | /// The ticket which will get enqueued. 27 | void Enqueue(Ticket ticket); 28 | 29 | /// 30 | /// Dequeues a from the . 31 | /// 32 | /// Returns the enqueued . 33 | Task DequeueAsync(CancellationToken ct); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/BackgroundTaskQueue/BackgroundQueue/BackgroundTaskQueue.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | using System.Threading; 4 | using System.Threading.Tasks; 5 | using BackgroundQueue.Models; 6 | 7 | namespace BackgroundQueue 8 | { 9 | public class BackgroundTaskQueue : IBackgroundTaskQueue 10 | { 11 | public bool IsDisposed { get; private set; } 12 | private readonly ConcurrentQueue _taskQueue; 13 | private readonly SemaphoreSlim _signal; 14 | 15 | public BackgroundTaskQueue() 16 | { 17 | _taskQueue = new ConcurrentQueue(); 18 | _signal = new SemaphoreSlim(0); 19 | } 20 | 21 | /// 22 | public void Enqueue(Func task) => Enqueue(task, exception => { }); 23 | 24 | /// 25 | public void Enqueue(Func task, Action exception) 26 | { 27 | Enqueue(new BaseTicket(task, exception)); 28 | } 29 | 30 | /// 31 | public void Enqueue(Ticket ticket) 32 | { 33 | _taskQueue.Enqueue(ticket); 34 | _signal.Release(); 35 | ticket.Enqueued(); 36 | } 37 | 38 | /// 39 | public async Task DequeueAsync(CancellationToken ct) 40 | { 41 | await _signal.WaitAsync(ct); 42 | _taskQueue.TryDequeue(out var ticket); 43 | 44 | return ticket; 45 | } 46 | 47 | public void Dispose() 48 | { 49 | if (!IsDisposed) 50 | { 51 | _signal.Dispose(); 52 | IsDisposed = true; 53 | } 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/BackgroundTaskQueue/BackgroundQueue/BackgroundQueue.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.1;netstandard2.0;netcoreapp3.1;net6.0 5 | preview 6 | enable 7 | 1.0.0.3 8 | Twenty 9 | Twenty 10 | BackgroundQueue 11 | BackgroundQueue is a simple way to queue background Tasks in ASP.Net Core and in .Net in general. 12 | Twenty 13 | https://github.com/TwentyFourMinutes/BackgroundQueue 14 | true 15 | true 16 | LICENSE 17 | queue background backgroundqueue aspnetcore aspnet 18 | Copyright ©2022 Twenty 19 | BackgroundQueue 20 | 21 | 22 | 23 | BackgroundQueue.xml 24 | 25 | 26 | 27 | 28 | all 29 | runtime; build; native; contentfiles; analyzers; buildtransitive 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | True 38 | 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /src/BackgroundTaskQueue/BackgroundQueue/BackgroundTaskQueueService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | using Microsoft.Extensions.Hosting; 5 | using Microsoft.Extensions.Logging; 6 | 7 | namespace BackgroundQueue 8 | { 9 | public class BackgroundTaskQueueService : BackgroundService 10 | { 11 | public IBackgroundTaskQueue TaskQueue { get; } 12 | private readonly ILogger _logger; 13 | 14 | public BackgroundTaskQueueService( 15 | ILogger logger, 16 | IBackgroundTaskQueue taskQueue 17 | ) 18 | { 19 | _logger = logger; 20 | TaskQueue = taskQueue; 21 | } 22 | 23 | public override Task StartAsync(CancellationToken ct) 24 | { 25 | _logger.LogInformation( 26 | $"Background Service {nameof(BackgroundTaskQueueService)} is starting..." 27 | ); 28 | 29 | return base.StartAsync(ct); 30 | } 31 | 32 | protected override async Task ExecuteAsync(CancellationToken ct) 33 | { 34 | _logger.LogInformation( 35 | $"Background Service {nameof(BackgroundTaskQueueService)} is running." 36 | ); 37 | 38 | while (!ct.IsCancellationRequested) 39 | { 40 | var ticket = await TaskQueue.DequeueAsync(ct); 41 | 42 | try 43 | { 44 | await ticket.ExecuteAsync(ct); 45 | } 46 | catch (Exception ex) 47 | { 48 | ticket.OnException(ex); 49 | _logger.LogError(ex, $"Error occurred while executing {nameof(ticket)}."); 50 | } 51 | } 52 | } 53 | 54 | public override Task StopAsync(CancellationToken ct) 55 | { 56 | _logger.LogInformation( 57 | $"Background Service {nameof(BackgroundTaskQueueService)} is stopping..." 58 | ); 59 | 60 | return base.StopAsync(ct); 61 | } 62 | 63 | public override void Dispose() 64 | { 65 | TaskQueue.Dispose(); 66 | base.Dispose(); 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/BackgroundTaskQueue/BackgroundQueue/Generic/BackgroundResultQueueService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | using Microsoft.Extensions.Hosting; 5 | using Microsoft.Extensions.Logging; 6 | 7 | namespace BackgroundQueue.Generic 8 | { 9 | public class BackgroundResultQueueService : BackgroundService 10 | { 11 | public IBackgroundResultQueue ResultQueue { get; } 12 | private readonly ILogger _logger; 13 | 14 | public BackgroundResultQueueService( 15 | ILogger logger, 16 | IBackgroundResultQueue taskQueue 17 | ) 18 | { 19 | _logger = logger; 20 | ResultQueue = taskQueue; 21 | } 22 | 23 | public override Task StartAsync(CancellationToken ct) 24 | { 25 | _logger.LogInformation( 26 | $"Background Service {nameof(BackgroundResultQueueService)} is starting..." 27 | ); 28 | 29 | return base.StartAsync(ct); 30 | } 31 | 32 | protected override async Task ExecuteAsync(CancellationToken ct) 33 | { 34 | _logger.LogInformation( 35 | $"Background Service {nameof(BackgroundResultQueueService)} is running." 36 | ); 37 | 38 | while (!ct.IsCancellationRequested) 39 | { 40 | var ticket = await ResultQueue.DequeueAsync(ct); 41 | 42 | try 43 | { 44 | await ticket.ProccessAsync(ct); 45 | } 46 | catch (Exception ex) 47 | { 48 | ticket.OnException(ex); 49 | _logger.LogError(ex, $"Error occurred while executing {nameof(ticket)}."); 50 | } 51 | } 52 | } 53 | 54 | public override Task StopAsync(CancellationToken ct) 55 | { 56 | _logger.LogInformation( 57 | $"Background Service {nameof(BackgroundResultQueueService)} is stopping..." 58 | ); 59 | 60 | return base.StopAsync(ct); 61 | } 62 | 63 | public override void Dispose() 64 | { 65 | ResultQueue.Dispose(); 66 | base.Dispose(); 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/BackgroundTaskQueue/BackgroundQueue/Generic/Models/Ticket.cs: -------------------------------------------------------------------------------- 1 | using System.Threading; 2 | using System.Threading.Tasks; 3 | 4 | namespace BackgroundQueue.Generic.Models 5 | { 6 | /// 7 | /// Inherit from this class, if you want to create a new Ticket, which should get enqueued in a BackgroundResultQueue. 8 | /// 9 | public abstract class Ticket : TicketBase 10 | { 11 | private readonly TaskCompletionSource _completionSource; 12 | internal Task SourceTask 13 | { 14 | get => _completionSource.Task; 15 | } 16 | 17 | public Ticket() 18 | { 19 | _completionSource = new TaskCompletionSource(); 20 | } 21 | 22 | /// 23 | /// Contains the core logic of the Ticket. 24 | /// 25 | public abstract Task ExecuteAsync(CancellationToken ct); 26 | 27 | internal override async Task ProccessAsync(CancellationToken ct) 28 | { 29 | try 30 | { 31 | await ExecuteAsync(ct); 32 | } 33 | catch 34 | { 35 | throw; 36 | } 37 | finally 38 | { 39 | _completionSource.TrySetResult(default); 40 | } 41 | } 42 | } 43 | 44 | /// 45 | /// Inherit from this class, if you want to create a new Ticket, which should get enqueued in a BackgroundResultQueue. 46 | /// 47 | public abstract class Ticket : TicketBase 48 | { 49 | private readonly TaskCompletionSource _completionSource; 50 | internal Task SourceTask 51 | { 52 | get => _completionSource.Task; 53 | } 54 | 55 | public Ticket() 56 | { 57 | _completionSource = new TaskCompletionSource(); 58 | } 59 | 60 | public abstract Task ExecuteAsync(CancellationToken ct); 61 | 62 | internal override async Task ProccessAsync(CancellationToken ct) 63 | { 64 | T result = default!; 65 | 66 | try 67 | { 68 | result = await ExecuteAsync(ct); 69 | } 70 | catch 71 | { 72 | throw; 73 | } 74 | finally 75 | { 76 | _completionSource.TrySetResult(result); 77 | } 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/BackgroundTaskQueue/BackgroundQueue/Generic/BackgroundResultQueue.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | using System.Threading; 4 | using System.Threading.Tasks; 5 | using BackgroundQueue.Generic.Models; 6 | 7 | namespace BackgroundQueue.Generic 8 | { 9 | public class BackgroundResultQueue : IBackgroundResultQueue 10 | { 11 | public bool IsDisposed { get; private set; } 12 | private readonly ConcurrentQueue _taskQueue; 13 | private readonly SemaphoreSlim _signal; 14 | 15 | public BackgroundResultQueue() 16 | { 17 | _taskQueue = new ConcurrentQueue(); 18 | _signal = new SemaphoreSlim(0); 19 | } 20 | 21 | /// 22 | public Task ProcessInQueueAsync(Func task) => 23 | ProcessInQueueAsync(task, ct => { }); 24 | 25 | /// 26 | public Task ProcessInQueueAsync( 27 | Func task, 28 | Action exception 29 | ) => ProcessInQueueAsync(new BaseTicket(task, exception)); 30 | 31 | /// 32 | public Task ProcessInQueueAsync(Ticket ticket) 33 | { 34 | _taskQueue.Enqueue(ticket); 35 | _signal.Release(); 36 | ticket.Enqueued(); 37 | 38 | return ticket.SourceTask; 39 | } 40 | 41 | /// 42 | public Task ProcessInQueueAsync(Func> task) => 43 | ProcessInQueueAsync(task, ct => { }); 44 | 45 | /// 46 | public Task ProcessInQueueAsync( 47 | Func> task, 48 | Action exception 49 | ) => ProcessInQueueAsync(new BaseTicket(task, exception)); 50 | 51 | /// 52 | public Task ProcessInQueueAsync(Ticket ticket) 53 | { 54 | _taskQueue.Enqueue(ticket); 55 | _signal.Release(); 56 | ticket.Enqueued(); 57 | 58 | return ticket.SourceTask; 59 | } 60 | 61 | /// 62 | public async Task DequeueAsync(CancellationToken ct) 63 | { 64 | await _signal.WaitAsync(ct); 65 | _taskQueue.TryDequeue(out var ticket); 66 | 67 | return ticket; 68 | } 69 | 70 | public void Dispose() 71 | { 72 | if (!IsDisposed) 73 | { 74 | _signal.Dispose(); 75 | IsDisposed = true; 76 | } 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/BackgroundTaskQueue/BackgroundQueue/Generic/IBackgroundResultQueue.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | using BackgroundQueue.Generic.Models; 5 | 6 | namespace BackgroundQueue.Generic 7 | { 8 | public interface IBackgroundResultQueue : IDisposable 9 | { 10 | /// 11 | /// Adds a new to the Queue, which will get processed in a background thread. This method will return when the task got processed. 12 | /// 13 | /// The Task which will get enqueued. 14 | Task ProcessInQueueAsync(Func task); 15 | 16 | /// 17 | /// Adds a new to the Queue, which will get processed in a background thread. This method will return when the task got processed. 18 | /// 19 | /// The Task which will get enqueued. 20 | /// A action which will get called, if the task fails. 21 | Task ProcessInQueueAsync(Func task, Action exception); 22 | 23 | /// 24 | /// Adds a new to the Queue, which will get processed in a background thread. This method will return when the ticket got processed. 25 | /// 26 | /// The Ticket which will get enqueued. 27 | Task ProcessInQueueAsync(Ticket ticket); 28 | 29 | /// 30 | /// Adds a new to the Queue, which will get processed in a background thread. This method will return when the task got processed. 31 | /// 32 | /// The Task which will get enqueued. 33 | Task ProcessInQueueAsync(Func> task); 34 | 35 | /// 36 | /// Adds a new to the Queue, which will get processed in a background thread. This method will return when the task got processed. 37 | /// 38 | /// The Task which will get enqueued. 39 | /// A action which will get called, if the task fails. 40 | Task ProcessInQueueAsync( 41 | Func> task, 42 | Action exception 43 | ); 44 | 45 | /// 46 | /// Adds a new to the Queue, which will get processed in a background thread. This method will return when the ticket got processed. 47 | /// 48 | /// The Ticket which will get enqueued. 49 | Task ProcessInQueueAsync(Ticket ticket); 50 | 51 | /// 52 | /// Dequeues a from the . 53 | /// 54 | /// Returns the enqueued . 55 | Task DequeueAsync(CancellationToken ct); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # BackgroundQueue 2 | 3 | Nuget Nuget GitHub issues 4 | 5 | BackgroundQueue is a simple way to queue background Tasks in ASP.Net Core and in .Net in general. 6 | You can download BackgroundQueue either from the Nuget Package Manager or from the official [nuget.org](https://www.nuget.org/packages/BackgroundQueue) website. 7 | 8 | ## About 9 | 10 | This package brings two useful queues with it, which both operate in the Background, that means that they do not block the current Thread. With these queues you can enqueue `Tasks` or `Tickets` which provide even more control. They are also fully thread save and come with a handy `IServiceCollection` extension. 11 | 12 | ## How to 13 | 14 | First up, you'll need to download the `BackgroundQueue` nuget package from one of the sources named above. After that you need to decide which one of the queues you need. 15 | 16 | ### Basic setup 17 | 18 | 1. In your `ConfigureServices` method you want to add `AddBackgroundTaskQueue` or `AddBackgroundResultQueue` depending on your needs. 19 | 20 | ```c# 21 | public void ConfigureServices(IServiceCollection services) 22 | { 23 | [...] 24 | services.AddBackgroundTaskQueue(); 25 | //Or 26 | services.AddBackgroundResultQueue(); 27 | } 28 | ``` 29 | 30 | 2. In your Controller constructor you need to request the queue implementation of your needs, e.g. `IBackgroundTaskQueue`/`IBackgroundResultQueue` .This would look something like the following. 31 | 32 | ```c# 33 | public class HomeController : Controller 34 | { 35 | private readonly IBackgroundTaskQueue _taskQueue; 36 | //Or 37 | private readonly IBackgroundResultQueue _resultQueue; 38 | 39 | public DashboardController(IBackgroundTaskQueue taskQueue 40 | //Or 41 | IBackgroundResultQueue resultQueue) 42 | { 43 | _taskQueue = taskQueue; 44 | //Or 45 | _resultQueue = resultQueue; 46 | } 47 | } 48 | ``` 49 | 50 | 3. In any Action you can now consume any of those queues and start enqueuing items. 51 | 52 | ```c# 53 | public async Task Index() 54 | { 55 | _taskQueue.Enqueue(async token => 56 | { 57 | await EmailSender.SendEmailAsync("Somone visited our website!"); 58 | }); // Will return immediately. 59 | 60 | //Or 61 | 62 | await _backgroundQueue.ProcessInQueueAsync(async token => 63 | { 64 | // I need to wait for any other items in this queue first! 65 | }); // Will continue after all other items, which are in front of it are processed. 66 | 67 | return View(); 68 | } 69 | ``` 70 | 71 | 72 | 73 | ### BackgroundTaskQueue 74 | 75 | The `BackgroundTaskQueue` is a queue which will enqueue items and immediately return to the current execution. You could use this queue for sending emails. 76 | 77 | ### BackgroundResultQueue 78 | 79 | The `BackgroundResultQueue` is a queue which will enqueue items and waits until the `Task`/`Ticket` finished processing including the result. You could use this queue, if you want requests to get processed step by step, but still want everything happen asynchronously. 80 | 81 | ## Notes 82 | 83 | If you feel like something is not working as intended or you are experiencing issues, feel free to create an issue. Also for feature requests just create an issue. For further information feel free to send me a mail to `twenty@translucent.at` or message me on Discord `24_minutes#7496`. 84 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015/2017 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # Visual Studio 2017 auto generated files 33 | Generated\ Files/ 34 | 35 | # MSTest test Results 36 | [Tt]est[Rr]esult*/ 37 | [Bb]uild[Ll]og.* 38 | 39 | # NUNIT 40 | *.VisualState.xml 41 | TestResult.xml 42 | 43 | # Build Results of an ATL Project 44 | [Dd]ebugPS/ 45 | [Rr]eleasePS/ 46 | dlldata.c 47 | 48 | # Benchmark Results 49 | BenchmarkDotNet.Artifacts/ 50 | 51 | # .NET Core 52 | project.lock.json 53 | project.fragment.lock.json 54 | artifacts/ 55 | **/Properties/launchSettings.json 56 | 57 | # StyleCop 58 | StyleCopReport.xml 59 | 60 | # Files built by Visual Studio 61 | *_i.c 62 | *_p.c 63 | *_i.h 64 | *.ilk 65 | *.meta 66 | *.obj 67 | *.iobj 68 | *.pch 69 | *.pdb 70 | *.ipdb 71 | *.pgc 72 | *.pgd 73 | *.rsp 74 | *.sbr 75 | *.tlb 76 | *.tli 77 | *.tlh 78 | *.tmp 79 | *.tmp_proj 80 | *.log 81 | *.vspscc 82 | *.vssscc 83 | .builds 84 | *.pidb 85 | *.svclog 86 | *.scc 87 | 88 | # Chutzpah Test files 89 | _Chutzpah* 90 | 91 | # Visual C++ cache files 92 | ipch/ 93 | *.aps 94 | *.ncb 95 | *.opendb 96 | *.opensdf 97 | *.sdf 98 | *.cachefile 99 | *.VC.db 100 | *.VC.VC.opendb 101 | 102 | # Visual Studio profiler 103 | *.psess 104 | *.vsp 105 | *.vspx 106 | *.sap 107 | 108 | # Visual Studio Trace Files 109 | *.e2e 110 | 111 | # TFS 2012 Local Workspace 112 | $tf/ 113 | 114 | # Guidance Automation Toolkit 115 | *.gpState 116 | 117 | # ReSharper is a .NET coding add-in 118 | _ReSharper*/ 119 | *.[Rr]e[Ss]harper 120 | *.DotSettings.user 121 | 122 | # JustCode is a .NET coding add-in 123 | .JustCode 124 | 125 | # TeamCity is a build add-in 126 | _TeamCity* 127 | 128 | # DotCover is a Code Coverage Tool 129 | *.dotCover 130 | 131 | # AxoCover is a Code Coverage Tool 132 | .axoCover/* 133 | !.axoCover/settings.json 134 | 135 | # Visual Studio code coverage results 136 | *.coverage 137 | *.coveragexml 138 | 139 | # NCrunch 140 | _NCrunch_* 141 | .*crunch*.local.xml 142 | nCrunchTemp_* 143 | 144 | # MightyMoose 145 | *.mm.* 146 | AutoTest.Net/ 147 | 148 | # Web workbench (sass) 149 | .sass-cache/ 150 | 151 | # Installshield output folder 152 | [Ee]xpress/ 153 | 154 | # DocProject is a documentation generator add-in 155 | DocProject/buildhelp/ 156 | DocProject/Help/*.HxT 157 | DocProject/Help/*.HxC 158 | DocProject/Help/*.hhc 159 | DocProject/Help/*.hhk 160 | DocProject/Help/*.hhp 161 | DocProject/Help/Html2 162 | DocProject/Help/html 163 | 164 | # Click-Once directory 165 | publish/ 166 | 167 | # Publish Web Output 168 | *.[Pp]ublish.xml 169 | *.azurePubxml 170 | # Note: Comment the next line if you want to checkin your web deploy settings, 171 | # but database connection strings (with potential passwords) will be unencrypted 172 | *.pubxml 173 | *.publishproj 174 | 175 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 176 | # checkin your Azure Web App publish settings, but sensitive information contained 177 | # in these scripts will be unencrypted 178 | PublishScripts/ 179 | 180 | # NuGet Packages 181 | *.nupkg 182 | # The packages folder can be ignored because of Package Restore 183 | **/[Pp]ackages/* 184 | # except build/, which is used as an MSBuild target. 185 | !**/[Pp]ackages/build/ 186 | # Uncomment if necessary however generally it will be regenerated when needed 187 | #!**/[Pp]ackages/repositories.config 188 | # NuGet v3's project.json files produces more ignorable files 189 | *.nuget.props 190 | *.nuget.targets 191 | 192 | # Microsoft Azure Build Output 193 | csx/ 194 | *.build.csdef 195 | 196 | # Microsoft Azure Emulator 197 | ecf/ 198 | rcf/ 199 | 200 | # Windows Store app package directories and files 201 | AppPackages/ 202 | BundleArtifacts/ 203 | Package.StoreAssociation.xml 204 | _pkginfo.txt 205 | *.appx 206 | 207 | # Visual Studio cache files 208 | # files ending in .cache can be ignored 209 | *.[Cc]ache 210 | # but keep track of directories ending in .cache 211 | !*.[Cc]ache/ 212 | 213 | # Others 214 | ClientBin/ 215 | ~$* 216 | *~ 217 | *.dbmdl 218 | *.dbproj.schemaview 219 | *.jfm 220 | *.pfx 221 | *.publishsettings 222 | orleans.codegen.cs 223 | 224 | # Including strong name files can present a security risk 225 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 226 | #*.snk 227 | 228 | # Since there are multiple workflows, uncomment next line to ignore bower_components 229 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 230 | #bower_components/ 231 | 232 | # RIA/Silverlight projects 233 | Generated_Code/ 234 | 235 | # Backup & report files from converting an old project file 236 | # to a newer Visual Studio version. Backup files are not needed, 237 | # because we have git ;-) 238 | _UpgradeReport_Files/ 239 | Backup*/ 240 | UpgradeLog*.XML 241 | UpgradeLog*.htm 242 | ServiceFabricBackup/ 243 | *.rptproj.bak 244 | 245 | # SQL Server files 246 | *.mdf 247 | *.ldf 248 | *.ndf 249 | 250 | # Business Intelligence projects 251 | *.rdl.data 252 | *.bim.layout 253 | *.bim_*.settings 254 | *.rptproj.rsuser 255 | 256 | # Microsoft Fakes 257 | FakesAssemblies/ 258 | 259 | # GhostDoc plugin setting file 260 | *.GhostDoc.xml 261 | 262 | # Node.js Tools for Visual Studio 263 | .ntvs_analysis.dat 264 | node_modules/ 265 | 266 | # Visual Studio 6 build log 267 | *.plg 268 | 269 | # Visual Studio 6 workspace options file 270 | *.opt 271 | 272 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 273 | *.vbw 274 | 275 | # Visual Studio LightSwitch build output 276 | **/*.HTMLClient/GeneratedArtifacts 277 | **/*.DesktopClient/GeneratedArtifacts 278 | **/*.DesktopClient/ModelManifest.xml 279 | **/*.Server/GeneratedArtifacts 280 | **/*.Server/ModelManifest.xml 281 | _Pvt_Extensions 282 | 283 | # Paket dependency manager 284 | .paket/paket.exe 285 | paket-files/ 286 | 287 | # FAKE - F# Make 288 | .fake/ 289 | 290 | # JetBrains Rider 291 | .idea/ 292 | *.sln.iml 293 | 294 | # CodeRush 295 | .cr/ 296 | 297 | # Python Tools for Visual Studio (PTVS) 298 | __pycache__/ 299 | *.pyc 300 | 301 | # Cake - Uncomment if you are using it 302 | # tools/** 303 | # !tools/packages.config 304 | 305 | # Tabs Studio 306 | *.tss 307 | 308 | # Telerik's JustMock configuration file 309 | *.jmconfig 310 | 311 | # BizTalk build output 312 | *.btp.cs 313 | *.btm.cs 314 | *.odx.cs 315 | *.xsd.cs 316 | 317 | # OpenCover UI analysis results 318 | OpenCover/ 319 | 320 | # Azure Stream Analytics local run output 321 | ASALocalRun/ 322 | 323 | # MSBuild Binary and Structured Log 324 | *.binlog 325 | 326 | # NVidia Nsight GPU debugger configuration file 327 | *.nvuser 328 | 329 | # MFractors (Xamarin productivity tool) working folder 330 | .mfractor/ 331 | -------------------------------------------------------------------------------- /src/BackgroundTaskQueue/BackgroundQueue/BackgroundQueue.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | BackgroundQueue 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | Adds a new to the Queue, which will get processed in a background thread. This method will return when the task got processed. 43 | 44 | The Task which will get enqueued. 45 | 46 | 47 | 48 | Adds a new to the Queue, which will get processed in a background thread. This method will return when the task got processed. 49 | 50 | The Task which will get enqueued. 51 | A action which will get called, if the task fails. 52 | 53 | 54 | 55 | Adds a new to the Queue, which will get processed in a background thread. This method will return when the ticket got processed. 56 | 57 | The Ticket which will get enqueued. 58 | 59 | 60 | 61 | Adds a new to the Queue, which will get processed in a background thread. This method will return when the task got processed. 62 | 63 | The Task which will get enqueued. 64 | 65 | 66 | 67 | Adds a new to the Queue, which will get processed in a background thread. This method will return when the task got processed. 68 | 69 | The Task which will get enqueued. 70 | A action which will get called, if the task fails. 71 | 72 | 73 | 74 | Adds a new to the Queue, which will get processed in a background thread. This method will return when the ticket got processed. 75 | 76 | The Ticket which will get enqueued. 77 | 78 | 79 | 80 | Dequeues a from the . 81 | 82 | Returns the enqueued . 83 | 84 | 85 | 86 | Inherit from this class, if you want to create a new Ticket, which should get enqueued in a BackgroundResultQueue. 87 | 88 | 89 | 90 | 91 | Contains the core logic of the Ticket. 92 | 93 | 94 | 95 | 96 | Inherit from this class, if you want to create a new Ticket, which should get enqueued in a BackgroundResultQueue. 97 | 98 | 99 | 100 | 101 | This class is only for internal use. 102 | 103 | 104 | 105 | 106 | Gets called when the gets enqueued. 107 | 108 | 109 | 110 | 111 | Gets called when the method errors out. 112 | 113 | 114 | 115 | 116 | Adds the required BackgroundResultQueue services. 117 | 118 | 119 | 120 | 121 | Adds a new to the Queue, which will get processed in a background thread. This method will return immediately. 122 | 123 | The Task which will get enqueued. 124 | 125 | 126 | 127 | Adds a new to the Queue, which will get processed in a background thread. This method will return immediately. 128 | 129 | The Task which will get enqueued. 130 | A action which will get called, if the task fails. 131 | 132 | 133 | 134 | Adds a new to the Queue, which will get processed in a background thread. This method will return immediately. 135 | 136 | The ticket which will get enqueued. 137 | 138 | 139 | 140 | Dequeues a from the . 141 | 142 | Returns the enqueued . 143 | 144 | 145 | 146 | Inherit from this class, if you want to create a new Ticket, which should get enqueued in a BackgroundTaskQueue. 147 | 148 | 149 | 150 | 151 | Gets called when the gets enqueued. 152 | 153 | 154 | 155 | 156 | Gets called when the method errors out. 157 | 158 | 159 | 160 | 161 | Contains the core logic of the Ticket. 162 | 163 | 164 | 165 | 166 | Adds the required BackgroundTaskQueue services. 167 | 168 | 169 | 170 | 171 | --------------------------------------------------------------------------------