[C#] C#使用semaphore 管理异步下载请求 →→→→→进入此内容的聊天室

来自 , 2021-01-31, 写在 C#, 查看 204 次.
URL http://www.code666.cn/view/d9a5cf48
  1.  var semaphor = new Semaphore(50, 50);  // We allow at most 50 threads for crawling
  2.             var resultPins = new List<Pin>();  // Results stored here
  3.             foreach (var pin in new HashSet<string>(pinIdList))
  4.             {
  5.                 semaphor.WaitOne();
  6.                 Console.Write(">");
  7.                 var pinClient = new WebClient();
  8.                 pinClient.DownloadStringCompleted += (sender, ex) =>
  9.                 {
  10.                     var html = ex.Result.Replace("\n", "");
  11.                     pinClient.Dispose();
  12.                     lock (pinIdList)
  13.                     {
  14.                          // do some post-processing and write back the results
  15.                     }
  16.                     Console.Write("<");
  17.                     semaphor.Release();
  18.                 };
  19.                 pinClient.DownloadStringAsync(new Uri(string.Format("http://pinterest.com/pin/{0}/", pin)));
  20.             }
  21.  
  22.             for (int i = 0; i < 50; i++) semaphor.WaitOne();    // Wait until the last thread ends.
  23.             semaphor.Dispose();
  24.             Console.WriteLine();
  25. //csharp/5228

回复 "C#使用semaphore 管理异步下载请求"

这儿你可以回复上面这条便签

captcha