Use Task.WaitAll() to handle awaited tasks?

后端 未结 2 672
小鲜肉
小鲜肉 2020-12-08 14:03

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

2条回答
  •  甜味超标
    2020-12-08 14:52

    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...
    

提交回复
热议问题