Capripio
Capripio

Reputation: 484

C#: Make Task run simultaneously

I am trying to run Several Tasks continously, non-stop. Here is my code:

int maxThread = 100;
Task[] tasks = new Task[maxThreads];
while(true)
{
   for(int i = 0;i<maxThreads;i++)
   {
     tasks[i] = new Task.Factory.StartNew(someTask);
   }
   Task.WaitAll(tasks);
}

So this function waits for all tasks to be completed and runs next batch of tasks. But I would like to start a task as soon as one is finished, without waiting for the other tasks.

Thanks!

Upvotes: 2

Views: 2811

Answers (2)

Howard
Howard

Reputation: 3858

I'd like to use this one. Attach tasks to its parent; it is easy. Like this.

Task t1 = new Task(()=>{
    // put your children tasks here.
    Task.Factory.StartNew(()=>{}, TaskCreationOptions.AttachedToParent);
});

t1.RunSynchronously();

// then start your next batch tasks.

Upvotes: 0

I4V
I4V

Reputation: 35363

I would use SemaphoreSlim

int maxThread = 100;
SemaphoreSlim sem = new SemaphoreSlim(maxThread);

while (true)
{
    sem.Wait();
    Task.Factory.StartNew(someTask)
                .ContinueWith(t => sem.Release());
}

Using Parallel.ForEach with var po = new ParallelOptions(){MaxDegreeOfParallelism = 100}; can be other alternative. But Parallel.ForEach doesn't guarantee it will use 100 Tasks for it.

Upvotes: 8

Related Questions