如何运行api调用并在c#中并行执行它们的响应?

时间:2016-09-06 11:40:44

标签: c# ruby parallel-processing

我来自红宝石背景。我有一个项目需要迁移到c#。它将进行数千次api服务呼叫。在ruby中,我使用Typhoeus Hydra来并行运行请求并并行执行响应。

注意:每个api调用都是独立的,每个调用之间没有依赖关系。

ruby​​的模板将是这样的

#typhoeus gem used to make api call
QUEUE = Typhoeus::Hydra.new
[1..100].each do |val|
  request = Typhoeus::Request.new("http://api.com/?value=#{val}")
  request.on_complete do |response|
    # code to be executed after each call
  end
  QUEUE.queue(request)
end

#run the queue will run 100 api calls in parallel and execute complete block in parallel
QUEUE.run

我不知道我必须在c#中使用async和await(TPL)。但我需要一些有用的好例子。

提前致谢

2 个答案:

答案 0 :(得分:1)

Shou应该看一下Parallel LINQ库(PLINQ)。

你可以这样做:

Parallel.ForEach(Enumerable.Range(1, 100), (val) => 
{
  // make syncron api call 
  WebClient webClient = new WebClient();
  var result = webClient.DownloadString(string.Format("http://api.com/?value={0}", val);
  // work on the result
});

答案 1 :(得分:1)

并行处理是一种选择;但是,它会不必要地阻塞线程。由于您的操作受I / O限制(命中HTTP API),因此异步并发是更好的选择。

首先,您要定义“下载和处理”操作:

private static HttpClient client = new HttpClient();
private static async Task DownloadAndProcessAsync(string value)
{
  var response = await client.GetStringAsync($"http://api.com/?value={value}");
  // Process response.
}

如果你想同时运行 all ,那么一个简单的Task.WhenAll就足够了:

var source = Enumerable.Range(1, 100);
var tasks = source.Select(v => DownloadAndProcessAsync(v.ToString()));
await Task.WhenAll(tasks);

有关async / await的详细信息,请参阅我的intro to async blog post(及其末尾的后续资源)。