Created
December 26, 2016 03:23
-
-
Save arxae/78563714c3cdcd7b397e93ed218e786e to your computer and use it in GitHub Desktop.
Loops over a list to keep tasks running with a max ammount
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Collections.Concurrent; | |
using System.Threading.Tasks; | |
using System.Threading; | |
namespace TestProject | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var tasks = new List<QueuedTask> | |
{ | |
new QueuedTask("Task 1"), new QueuedTask("Task 2"), new QueuedTask("Task 3"), | |
new QueuedTask("Task 4"), new QueuedTask("Task 5"), new QueuedTask("Task 6"), | |
new QueuedTask("Task 7"), new QueuedTask("Task 8"), new QueuedTask("Task 9"), | |
new QueuedTask("Task 10") | |
}; | |
var tqr = new TaskQueueRunner(3, tasks); | |
Console.ReadKey(); | |
} | |
} | |
public class TaskQueueRunner | |
{ | |
public bool IsRunning { get; private set; } | |
public IEnumerable<QueuedTask> AllTasks { get; private set; } | |
private ConcurrentQueue<QueuedTask> _taskQueue; | |
public SemaphoreSlim _taskSemaphore; | |
public TaskQueueRunner(int MaxTasks, IEnumerable<QueuedTask> tasks, bool autoStart = true) | |
{ | |
AllTasks = tasks; | |
_taskQueue = new ConcurrentQueue<QueuedTask>(AllTasks); | |
_taskSemaphore = new SemaphoreSlim(MaxTasks); | |
if (autoStart) | |
{ | |
Start(); | |
} | |
} | |
public void Start() | |
{ | |
if (IsRunning == false) | |
{ | |
IsRunning = true; | |
_run(); | |
} | |
} | |
public void Stop() | |
{ | |
IsRunning = false; | |
} | |
void _run() | |
{ | |
while (IsRunning) | |
{ | |
_taskSemaphore.Wait(); | |
Task.Run(() => | |
{ | |
// Refill queue when empty | |
if (_taskQueue.IsEmpty) | |
{ | |
_taskQueue = new ConcurrentQueue<QueuedTask>(AllTasks); | |
} | |
QueuedTask task; | |
if (_taskQueue.TryDequeue(out task)) | |
{ | |
Console.Write($"Count: {_taskQueue.Count} | "); | |
task.Execute(); | |
} | |
}) | |
.ContinueWith(_ => _taskSemaphore.Release()); | |
} | |
} | |
} | |
public class QueuedTask | |
{ | |
public string Message { get; set; } | |
public QueuedTask(string msg) | |
{ | |
Message = msg; | |
} | |
public void Execute() | |
{ | |
Console.WriteLine(Message); | |
Thread.Sleep(500); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment