【问题标题】:Call methods parallel and combine results并行调用方法并合并结果
【发布时间】:2015-05-15 13:56:03
【问题描述】:

我有一个 MainMethod 需要并行调用两个方法 Method1 和 Method2。他们都将返回员工列表,但来自不同的数据库。我需要并行调用它们,然后在 MainMethod 中合并 Method1 和 Method2 的结果,然后将结果返回给 MainMethod 的调用者。

如果人们能说出方法的签名必须是什么以及我需要编写什么代码,我的意思是异步/等待关键字,我非常感激。

【问题讨论】:

  • 为什么“需要”它们并行?这是一个副本:stackoverflow.com/questions/7320491/…
  • @DStanley - Parallel.Invoke 不是收集结果的方式。
  • @DStanley 也不保证并行运行。
  • 代码根本不保证运行 - 确保如果您使用new Task 调用Task.Start 执行任务。此外,由于您在执行 get 方法时锁定,长时间运行的部分可能不会并行运行,尽管它会得到正确的结果。
  • 这个锁在技术上是正确的,因为它可以防止对结果的多次访问。但是,正如我和@HenkHolterman 在我们的回答者中所做的那样,最好让每个任务运行,获得结果,然后将这些结果连接起来,而不是添加到内联的单一缓冲区。更少的锁定,更少的陷阱(如果你的查询返回一个IEnumerable<>,它可能直到迭代才真正执行,这仍然可以在锁定中工作)。

标签: c# parallel-processing


【解决方案1】:

使用更多的速记...

public static async Task<IEnumerable<Employee>> MainMethod()
{
    // Await when all to get an array of result sets after all of then have finished
    var results = await Task.WhenAll(
        Task.Run(() => Method1()), // Note that this leaves room for parameters to Method1...
        Task.Run(Method2)          // While this shorthands if there are no parameters
        // Any further method calls can go here as more Task.Run calls
        );

    // Simply select many over the result sets to get each result
    return results.SelectMany(r => r);
}

对于签名参考,它使用以下 .NET 函数:

【讨论】:

  • 你能告诉我 Method1() 和 Method2() 的签名是什么。请你写完整的代码。
  • Method1Method2 只是示例,取自该问题的原始写作。不过,我可以添加签名
【解决方案2】:

您可以将它们作为 2 Task&lt;T&gt;s 运行。 Result 属性负责等待。大约:

// untested 
Task<List<Employee>> t1 = Task.Factory.StartNew(() => Method1());
Task<List<Employee>> t2 = Task.Factory.StartNew(() => Method2());

var result = t1.Result.Concat(t2.Result);

【讨论】:

  • Henk... 你能告诉我 Method1() 或 Method2() 的签名必须是什么,以及如何从它们返回结果以及我需要使用的任何 async/await 关键字。跨度>
  • 他们只需要返回List&lt;Employee&gt;。无需等待。
  • Henk.. 请查看我的更新问题。我添加了我编写的示例代码。对吗?
  • 是的,它看起来正确,但既不短也不高效。 Task 方法出了什么问题?
  • 我不知道为什么我的问题被编辑了。它清楚地具有我编写的完整代码,以便其他人可以使用它。但这是我的方法 private static List Method1() 和 private static List Method2() 的签名
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-07
  • 2016-07-04
  • 2013-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多