Ideally what I want to do is to delay a task with a non-blocking mode and then wait for all the tasks to complete. I've tried to add the task object returned by Task.Delay and then use Task.WaitAll but seems this won't help. How should I solve this problem?
class Program { public static async void Foo(int num) { Console.WriteLine("Thread {0} - Start {1}", Thread.CurrentThread.ManagedThreadId, num); var newTask = Task.Delay(1000); TaskList.Add(newTask); await newTask; Console.WriteLine("Thread {0} - End {1}", Thread.CurrentThread.ManagedThreadId, num); } public static List<Task> TaskList = new List<Task>(); public static void Main(string[] args) { for (int i = 0; i < 3; i++) { int idx = i; TaskList.Add(Task.Factory.StartNew(() => Foo(idx))); } Task.WaitAll(TaskList.ToArray()); } }
WhenAll we will get a task object that isn't complete. However, it will not block but will allow the program to execute. On the contrary, the Task. WaitAll method call actually blocks and waits for all other tasks to complete.
WaitAll(Task[], TimeSpan)Waits for all of the provided cancellable Task objects to complete execution within a specified time interval.
The static Task. WaitAll() method is used to wait for a number of tasks to complete, so it will not return until all the given tasks will either complete, throw an exception or be cancelled.
Task. WhenAll creates a task that will complete when all of the supplied tasks have been completed. It's pretty straightforward what this method does, it simply receives a list of Tasks and returns a Task when all of the received Tasks completes.
Is this what you are trying to achieve?
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace ConsoleApplication { class Program { public static async Task Foo(int num) { Console.WriteLine("Thread {0} - Start {1}", Thread.CurrentThread.ManagedThreadId, num); await Task.Delay(1000); Console.WriteLine("Thread {0} - End {1}", Thread.CurrentThread.ManagedThreadId, num); } public static List<Task> TaskList = new List<Task>(); public static void Main(string[] args) { for (int i = 0; i < 3; i++) { int idx = i; TaskList.Add(Foo(idx)); } Task.WaitAll(TaskList.ToArray()); Console.WriteLine("Press Enter to exit..."); Console.ReadLine(); } } }
Output:
Thread 10 - Start 0 Thread 10 - Start 1 Thread 10 - Start 2 Thread 6 - End 0 Thread 6 - End 2 Thread 6 - End 1 Press Enter to exit...
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