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?
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.
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.
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.
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.
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() ); }
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; }
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