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
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 TaskList = new List();
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...