Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Have a set of Tasks with only X running at a time

Let's say I have 100 tasks that do something that takes 10 seconds. Now I want to only run 10 at a time like when 1 of those 10 finishes another task gets executed till all are finished.

Now I always used ThreadPool.QueueUserWorkItem() for such task but I've read that it is bad practice to do so and that I should use Tasks instead.

My problem is that I nowhere found a good example for my scenario so could you get me started on how to achieve this goal with Tasks?

like image 541
maddo7 Avatar asked Dec 28 '12 19:12

maddo7


People also ask

How many tasks can be created C#?

The general answer is "Measure, Measure, Measure" :) if you're not experiencing any problems with performance, you shouldn't start optimizing. I'd say 200 tasks are fine though.

What is a continuation task?

A continuation task (also known just as a continuation) is an asynchronous task that's invoked by another task, known as the antecedent, when the antecedent finishes.

How can I run two functions at the same time in C#?

In C#, the Thread class represents a thread. The constructor of the Thread class takes a method that will be executed when a thread starts. In the code listed below, I create two threads and call the Start method to start executing them simultaneously.

Does task WhenAll run in parallel?

WhenAll() method in . NET Core. This will upload the first file, then the next file. There is no parallelism here, as the “async Task” does not automatically make something run in in parallel.


2 Answers

SemaphoreSlim maxThread = new SemaphoreSlim(10);  for (int i = 0; i < 115; i++) {     maxThread.Wait();     Task.Factory.StartNew(() =>         {             //Your Works         }         , TaskCreationOptions.LongRunning)     .ContinueWith( (task) => maxThread.Release() ); } 
like image 135
L.B Avatar answered Sep 23 '22 08:09

L.B


TPL Dataflow is great for doing things like this. You can create a 100% async version of Parallel.Invoke pretty easily:

async Task ProcessTenAtOnce<T>(IEnumerable<T> items, Func<T, Task> func) {     ExecutionDataflowBlockOptions edfbo = new ExecutionDataflowBlockOptions     {          MaxDegreeOfParallelism = 10     };      ActionBlock<T> ab = new ActionBlock<T>(func, edfbo);      foreach (T item in items)     {          await ab.SendAsync(item);     }      ab.Complete();     await ab.Completion; } 
like image 29
Cory Nelson Avatar answered Sep 19 '22 08:09

Cory Nelson