This application demonstrates the implementation of a queue data structure in C#. It provides basic operations such as enqueue and dequeue
- Enqueue: Add an element to the end of the queue.
- Dequeue: Remove and return the element at the front of the queue.
- enqueued actions will run as fire and forget tasks
- .NET Core 7+ (change
TargetFrameworkon .csproj file)
- Clone the repository:
git clone https://github.com/yourusername/csharp_queue.git
- Navigate to the project directory:
cd csharp_queue - Build the project:
dotnet build
- Run the application:
dotnet run
The application provides a web api interface to interact with the queue. Follow the on-screen instructions to perform various queue operations.
- Uses
QueuedBackgroundServiceHostedService from Microsoft. It runs on a loop to wait for any queue items. - Create a queue using
IBackgroundTaskQueue.QueueBackgroundWorkItem
private readonly IBackgroundTaskQueue _taskQueue;
public ExampleController(IBackgroundTaskQueue taskQueue)
{
_taskQueue = taskQueue;
}
[HttpPost("fire-and-forget")]
public IActionResult FireAndForget([FromQuery] string message)
{
_taskQueue.QueueBackgroundWorkItem(async token =>
{
await Task.Delay(5000, token); // Simulated work
Console.WriteLine($"Background task completed: {message}");
});
return Accepted(new { Message = "Background task queued" });
}- It uses
SemaphoreSlimto handle access to the queue. Once it gives access theQueuedBackgroundServicewill run the action given to it.
Note: do not use any top level objects on the queued action. This will throw exception as the object will be disposed.