I have a program where I let the user create several functions and once he creates all the functions I run them every x milliseconds. In other words I have something like:
// functionsToExecute is of type = List<Action>
// x = some integer
while(true){
foreach(Action action in functionsToExecute)
{
action();
}
Thread.Sleep(x);
}
Now I will like for the user to decide how long to wait per function. For example if the user creates 2 functions he might want the first function to run every 500 milliseconds the next one every 1500. I was thinking about creating two threads for this scenario and then have the same implementation. But what if the user creates 50 functions? I will need 50 threads!
In short I will like to execute x number of Actions each every n milliseconds… What will be the best way to create such algorithm? For example if I have 3 Actions I will like to execute the first action every 200 milliseconds, the next one every 500 milliseconds and the last one every 1000 milliseconds.
Maybe I need something similar to the SetTimout function in javascript
If you’re using .NET 4.5 and your code is not time-critical, then you can easily do this with the Task Parallel Library:
Ideally, you should also make your actions async to properly support cancellation.
The .NET runtime automatically takes care of thread scheduling, but there’s no guarantee that your action will be executed after exactly the requested timeout. It will be executed after at least that time has elapsed and there’s an idle thread available.