Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Threading.Tasks - Limit the number of concurrent Tasks

I have just started to look at the new "System.Threading.Tasks" goodness in .Net 4.0, and would like to know if there is any build in support for limiting the number of concurrent tasks that run at once, or if this should be manually handled.

E.G: If I need to call a calculation method 100 times, is there a way to set up 100 Tasks, but have only 5 execute simultaneously? The answer may just be to create 5 tasks, call Task.WaitAny, and create a new Task as each previous one finishes. I just want to make sure I am not missing a trick if there is a better way to do this.

Basically, is there a built in way to do this:

Dim taskArray() = {New Task(Function() DoComputation1()),                    New Task(Function() DoComputation2()),                    ...                    New Task(Function() DoComputation100())}  Dim maxConcurrentThreads As Integer = 5 RunAllTasks(taskArray, maxConcurrentThreads) 

Thanks for any help.

like image 649
James Avatar asked May 24 '10 16:05

James


People also ask

What are concurrent tasks?

Concurrent tasks are multiple tasks that progress at the same time in the worker system but are not executed simultaneously. The worker system switches between tasks until all the tasks are completed or it can work sequentially by completing one task before moving to the next task.

Why we use using system threading tasks in C#?

Tasks Namespace. Provides types that simplify the work of writing concurrent and asynchronous code. The main types are Task which represents an asynchronous operation that can be waited on and cancelled, and Task<TResult>, which is a task that can return a value.

What is the difference between threads and tasks?

A thread is one of the many possible workers which performs that task. In . NET 4.0 terms, a Task represents an asynchronous operation. Thread(s) are used to complete that operation by breaking the work up into chunks and assigning to separate threads.

Is task better than thread?

It is always advised to use tasks instead of thread as it is created on the thread pool which has already system created threads to improve the performance. The task can return a result. There is no direct mechanism to return the result from a thread. Task supports cancellation through the use of cancellation tokens.


1 Answers

I know this is almost a year old, but I have found a much easier way to achieve this, so I thought I would share:

Dim actionsArray() As Action =       new Action(){          New Action(Sub() DoComputation1()),          New Action(Sub() DoComputation2()),          ...          New Action(Sub() DoComputation100())       }  System.Threading.Tasks.Parallel.Invoke(New Tasks.ParallelOptions() With {.MaxDegreeOfParallelism = 5}, actionsArray) 

Voila!

like image 84
James Avatar answered Oct 08 '22 03:10

James