假设我有两个类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>
。但是这种方法会返回嵌套的void* p = (void*)myString.GetBuffer(1);
...
myString.ReleaseBuffer();
,这可能不是最佳的。
答案 0 :(得分:3)
我认为你对语法有点困惑。这应该是你要找的东西:
// 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));