Ok, so basically I have a bunch of tasks (10) and I want to start them all at the same time and wait for them to complete. When completed I want to execute other tasks. I read a bunch of resources about this but I can't get it right for my particular case...
Here is what I currently have (code has been simplified):
public async Task RunTasks() { var tasks = new List<Task> { new Task(async () => await DoWork()), //and so on with the other 9 similar tasks } Parallel.ForEach(tasks, task => { task.Start(); }); Task.WhenAll(tasks).ContinueWith(done => { //Run the other tasks }); } //This function perform some I/O operations public async Task DoWork() { var results = await GetDataFromDatabaseAsync(); foreach (var result in results) { await ReadFromNetwork(result.Url); } }
So my problem is that when I'm waiting for tasks to complete with the WhenAll
call, it tells me that all tasks are over even though none of them are completed. I tried adding Console.WriteLine
in my foreach
and when I have entered the continuation task, data keeps coming in from my previous Task
s that aren't really finished.
What am I doing wrong here?
Parallel tasks are split into subtasks that are assigned to multiple workers and then completed simultaneously. A worker system can carry out both parallel and concurrent tasks by working on multiple tasks at the same time while also breaking down each task into sub-tasks that are executed simultaneously.
There is no parallelism here, as the “async Task” does not automatically make something run in in parallel. This will spawn 2 threads, run them simultaneously, and return when both threads are done. This will create a list of Tasks to be run at the same time.
Task parallelism is the process of running tasks in parallel. Task parallelism divides tasks and allocates those tasks to separate threads for processing. It is based on unstructured parallelism.
You should almost never use the Task
constructor directly. In your case that task only fires the actual task that you can't wait for.
You can simply call DoWork
and get back a task, store it in a list and wait for all the tasks to complete. Meaning:
tasks.Add(DoWork()); // ... await Task.WhenAll(tasks);
However, async methods run synchronously until the first await on an uncompleted task is reached. If you worry about that part taking too long then use Task.Run
to offload it to another ThreadPool
thread and then store that task in the list:
tasks.Add(Task.Run(() => DoWork())); // ... await Task.WhenAll(tasks);
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