假设我有两个类A
和B
派生自一个接口(例如IAorB
)。 A
包含IAorB
对象的列表:
public interface IAorB { ... }
public class A
{
...
public List<IAorB> Children { get; set; }
...
}
public class B { ... }
如果我想异步地将操作应用于
IAorB
对象及其所有子对象(如果有),是否建议采用以下方法?如果没有,是否有更好的方法?public Task SomeOperation(IAorB object) { ... } //May take some time
public Task<List<Task>> OperateRecursively(A root)
{
List<Task> tasks = new List<Task>();
foreach (IAorB child in root.Children)
{
if (child.GetType() == typeof(B))
{
tasks.Add(SomeOperation(child));
}
else
{
tasks.Add(OperateRecursively(child as A));
}
}
tasks.Add(SomeOperation(root));
return tasks;
}
最佳地,
OperateRecursively
将返回List
的Tasks
,我可以在其中使用Task.WaitAll()
。但是这种方法返回嵌套的List<Task>
,这可能不是最佳选择。 最佳答案
我想您只是对语法有点困惑。这应该是您要寻找的:
// fix method signature, this doesn't run asynchronous code so it needs not be a Task
public IEnumerable<Task> OperateRecursively(A root)
{
List<Task> tasks = new List<Task>();
foreach (IAorB child in root.Children)
{
if (child is B)
{
tasks.Add(SomeOperation(child));
}
else
{
// 1. change to AddRange since you are adding multiple elements, not one
// 2. fix name for actual recursion
// 3. cast child to A since otherwise it wouldn't compile
tasks.AddRange(OperateRecursivelyA(child as A));
}
}
tasks.Add(SomeOperation(root));
return tasks;
}
然后您将简单地用作
await Task.WhenAll(OperateRecursivelyA(someRoot));