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.
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.
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.
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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With