1

I have been trying to do this:

Create 'N' Task to execute and keep running this number of taks for a period of time, in that case the one task finalize, then i should start a new task to keep the same number of task.

I dont know if is this possible to handle with TaskScheduler or i have to create a custom TaskScheduler.

Another option i think could work is , use TPL DataFlow Producer-Consumer when the task finish then taskscheduler take a new task generate by producer.

The question is: how can i create a new task when one finished to keep the same number of tasks?

svick
  • 236,525
  • 50
  • 385
  • 514
Lu1zZz
  • 57
  • 2
  • 10
  • And the question is....? – tnw Jan 10 '14 at 19:33
  • TPL DataFlow's `ActionBlock` can have a defined degree of paralleism. Meaning, if you want 5 tasks running at once... and then once one finishes, it will grab the next available task to run that. – poy Jan 10 '14 at 19:36
  • It sounds like you're misusing Tasks. What are you trying to accomplish? – SLaks Jan 10 '14 at 19:37
  • Yeah, maybe i could use on the wrong way tasks, but i dont want use threads, My accomplish is to stress a one server create a N requests, but i should keep 'running' a specific numbers of request for a period of time. – Lu1zZz Jan 10 '14 at 19:43
  • Look into Parallel.ForEach and PLINQ. That's likely to trivially solve your problem. – usr Jan 10 '14 at 19:43
  • Doesn't threadpool do this? Set a max number for the threadpool and have at it. Except a thread and a task are different... – Felix Castor Jan 10 '14 at 19:43
  • So make N tasks, and put an infinite loop in each one. – SLaks Jan 10 '14 at 20:22

2 Answers2

8

This code will keep running numTasks Tasks in parallel.

int numTasks = 5;
SemaphoreSlim semaphore = new SemaphoreSlim(numTasks);
while(true)
{
    semaphore.Wait();
    Task.Run(() =>
        {
            DoSomething();
        })
        .ContinueWith(_ => semaphore.Release());
}
L.B
  • 114,136
  • 19
  • 178
  • 224
  • I love this idea, but how could you do this with asynchronous tasks? –  Aug 01 '18 at 19:51
0

Task scheduler could be used to run an executable that you could use to perform a set of work/tasks. Alternatively, you could simply create a windows service...

xspydr
  • 3,030
  • 3
  • 31
  • 49