理想情况下,我想做的是以非阻塞模式延迟任务,然后等待所有任务完成。我试图添加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();
}
}
}
输出:
线程10-开始0 线程10-开始1 线程10-开始2 线程6-结束0 线程6-结束2 线程6-结束1 按Enter退出...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句