小编Act*_*ary的帖子

parallel.foreach和httpclient - 奇怪的行为

我有一段代码循环遍历集合,并为每次迭代调用httpclient.httpclient调用的api平均需要30-40ms才能执行.顺序调用它,我得到预期的结果,但是一旦我使用Parallel.foreach,它需要更长的时间.仔细查看日志,我可以看到很多httpclient调用需要1000ms才能执行,然后时间会回落到30-40ms.查看api日志,我可以看到它几乎没有超过100毫秒.我不知道为什么我会得到这个高峰.

代码是

using (var client = new HttpClient())
{
  var content = new StringContent(parameters, Encoding.UTF8, "application/json");
  var response = client.PostAsync(url, content);
  _log.Info(string.Format("Took {0} ms to send post", watch.ElapsedMilliseconds));
  watch.Restart();

  var responseString = response.Result.Content.ReadAsStringAsync();
  _log.Info(string.Format("Took {0} ms to readstring after post", watch.ElapsedMilliseconds));
}
Run Code Online (Sandbox Code Playgroud)

并行调用是这样的

    Console.WriteLine("starting parallel...");
    Parallel.ForEach(recipientCollections, recipientCollection => 
      {    
        // A lot of processing happens here to create relevant content
        var secondaryCountryRecipientList = string.Join(",",refinedCountryRecipients);
        var emailApiParams = new SendEmailParametersModel(CountrySubscriberApplicationId,
                                        queueItem.SitecoreId, queueItem.Version, queueItem.Language, countryFeedItem.Subject,
                                        countryFeedItem.Html, countryFeedItem.From, _recipientsFormatter.Format(secondaryCountryRecipientList));

       log.Info(string.Format("Sending email request for …
Run Code Online (Sandbox Code Playgroud)

c# parallel-processing asp.net-web-api2

4
推荐指数
2
解决办法
2491
查看次数

标签 统计

asp.net-web-api2 ×1

c# ×1

parallel-processing ×1