c# - 使用 Task.WaitAll() 来处理等待的任务?

标签 c# multithreading async-await

理想情况下我想做的是用非阻塞模式延迟一个任务,然后等待所有任务完成。我试图添加 Task.Delay 返回的任务对象,然后使用 Task.WaitAll 但这似乎无济于事。我该如何解决这个问题?

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

最佳答案

这就是您要实现的目标吗?

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

输出:

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

关于c# - 使用 Task.WaitAll() 来处理等待的任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19849847/

相关文章:

c# - 功能 'interpolated strings' 在 C# 5 中不可用。请使用语言版本 6 或更高版本

c# - 使用 SetupGet 和 SetupSet 模拟属性 - 这可行,但为什么呢?

python - python线程中的信号中断

c# - 为什么从 Async CTP/Release 中删除 "SwitchTo"?

c# - 从后面的代码向图例添加文本

c# - 以编程方式获取 nUnit 选择的类别

java - 停止线程列表

C线程池效率

c# - 异步 EF 任务的同步

c# - 异步等待在 C# 中丢失响应