使用任务<list <task>&gt;用于C#中的异步递归操作

时间:2018-03-28 23:41:44

标签: c# asynchronous recursion task

假设我有两个类AB来自一个接口(比如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(); ,这可能不是最佳的。

1 个答案:

答案 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));