我有以下代码:
static void Main(string[] args)
{
TaskExecuter.Execute();
}
class Task
{
int _delay;
private Task(int delay) { _delay = delay; }
public void Execute() { Thread.Sleep(_delay); }
public static IEnumerable GetAllTasks()
{
Random r = new Random(4711);
for (int i = 0; i < 10; i++)
yield return new Task(r.Next(100, 5000));
}
}
static class TaskExecuter
{
public static void Execute()
{
foreach (Task task in Task.GetAllTasks())
{
task.Execute();
}
}
}
我需要将 Execute 方法中的循环更改为与多个线程并行,我尝试了以下操作,但它不起作用,因为 GetAllTasks 返回 IEnumerable 而不是列表
Parallel.ForEach(Task.GetAllTasks(), task =>
{
//Execute();
});