I have a Windows service application that has a number of different jobs that need to be done in parallel and are spawned on three different schedules. However I want to make sure that at no point of time more than N tasks are running.
This is not a duplicate of this question, because that is about limiting the number of tasks that are started per second, not the number that are running concurrently. Also not a duplicate of this because my tasks are on separate schedules so cannot be queued simultaneously.
Here is some code to provide context:
namespace WindowsService1
{
public partial class Service1 : ServiceBase
{
List<Task> ServiceTasks;
private List<Timer> ServiceTimers;
private static int N = 10;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
List<double> Times = new List<double>(){1000d,2000d,5000d};
for(int i = 0; i<3 ; i++)
{
var t = new Timer(Times[i]);
t.AutoReset = true;
ServiceTimers.Add(t);
}
ServiceTimers[0].Elapsed += Timer1Elapsed_DoSomething;
ServiceTimers[0].Start();
ServiceTimers[1].Elapsed += Timer2Elapsed_DoSomething;
ServiceTimers[1].Start();
ServiceTimers[2].Elapsed += Timer3Elapsed_DoSomething;
ServiceTimers[2].Start();
}
private void Timer1Elapsed_DoSomething(object sender, ElapsedEventArgs e)
{
ServiceTasks.Add(Task.Factory.StartNew(() => ServiceWork.DoTask1()));
}
private void Timer2Elapsed_DoSomething(object sender, ElapsedEventArgs e)
{
ServiceTasks.Add(Task.Factory.StartNew(() => ServiceWork.DoTask2()));
}
private void Timer3Elapsed_DoSomething(object sender, ElapsedEventArgs e)
{
ServiceTasks.Add(Task.Factory.StartNew(() => ServiceWork.DoTask3()));
}
}
}
How can I modify this code to ensure that only N tasks will be running at any given time?