The next generation of the Teknik Services. Written in ASP.NET. https://www.teknik.io/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

BackgroundTaskQueue.cs 1.0KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Text;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. namespace Teknik.Utilities
  8. {
  9. public class BackgroundTaskQueue : IBackgroundTaskQueue
  10. {
  11. private ConcurrentQueue<Func<CancellationToken, Task>> _workItems =
  12. new ConcurrentQueue<Func<CancellationToken, Task>>();
  13. private SemaphoreSlim _signal = new SemaphoreSlim(0);
  14. public void QueueBackgroundWorkItem(
  15. Func<CancellationToken, Task> workItem)
  16. {
  17. if (workItem == null)
  18. {
  19. throw new ArgumentNullException(nameof(workItem));
  20. }
  21. _workItems.Enqueue(workItem);
  22. _signal.Release();
  23. }
  24. public async Task<Func<CancellationToken, Task>> DequeueAsync(
  25. CancellationToken cancellationToken)
  26. {
  27. await _signal.WaitAsync(cancellationToken);
  28. _workItems.TryDequeue(out var workItem);
  29. return workItem;
  30. }
  31. }
  32. }