使用C#执行不确定的任务列表

问题描述

我遇到了一些需要被激发的数据库查询的情况。其中一些要求运行上一个查询的结果,从而形成各种层次结构。

我想要这样,以便在1个查询完成时,我可以处理该数据,而无需等待子查询完成。如果查询未返回任何数据,则层次结构也可能会提早停止。

我不需要/希望将最终结果作为层次结构,因此将结果展平是目标(类似于示例中的List )。

为了简单起见,我已经更改了一些内容,但是我目前的基本要旨是:

private static async Task ProcessQueries(Foo initialFoo)
{
    var allEntities = new List<IEnumerable<object>>();
    var runningProcesses = new List<Task<Bar>>();
    var queriesToProcess = new Queue<Foo>();
    queriesToProcess.Enqueue(initialFoo);

    while (runningProcesses.Count > 0 || queriesToProcess.Count > 0)
    {
        while (queriesToProcess.Count > 0)
        {
            var fooToProcess = queriesToProcess.Dequeue();
            runningProcesses.Add(ProcessFoo(fooToProcess));
        }

        // As soon as any of the 'ProcessFoo' have finished,it means the query for the entities has finished
        // And it might have more Foo's for us to process.
        // I want to call ProcessFoo as soon as possible as that actually starts the query.
        var finishedProcess = await Task.WhenAny(runningProcesses).ConfigureAwait(false);
        runningProcesses.Remove(finishedProcess);

        var finishedFoo = finishedProcess.Result;
        foreach (var childFoo in finishedFoo.ChildFoos)
        {
            queriesToProcess.Enqueue(childFoo);
        }

        // I can Now pass the entities to something else to process it without stopping the loop
        // In this example I just add it to the list
        allEntities.Add(finishedFoo.Entities);
    }
}

Foo仅包含开始查询所需的所有信息。

栏包含实体,以及要运行的其他Foo的列表。


如果potential issues with Task.WhenAny太大,我会读到它。我认为他的解决方案不适用于我,因为我的任务列表不是固定大小的。

我想知道是否有更有效的方法来实现这一目标?或是否有此类工作的现有设计?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)