Run async method 8 times in parallel

前端 未结 4 1166
再見小時候
再見小時候 2020-12-01 16:59

How do I turn the following into a Parallel.ForEach?

public async void getThreadContents(String[] threads)
{
    HttpClient client = new HttpClient();
    Li         


        
4条回答
  •  无人及你
    2020-12-01 17:45

    Yet another alternative is using SemaphoreSlim or AsyncSemaphore (which is included in my AsyncEx library and supports many more platforms than SemaphoreSlim):

    public async Task getThreadContentsAsync(String[] threads)
    {
      SemaphoreSlim semaphore = new SemaphoreSlim(8);
      HttpClient client = new HttpClient();
      ConcurrentDictionary usernames = new ConcurrentDictionary();
    
      await Task.WhenAll(threads.Select(async url =>
      {
        await semaphore.WaitAsync();
        try
        {
          HttpResponseMessage response = await client.GetAsync(url);
          String content = await response.Content.ReadAsStringAsync();
          String user;
          foreach (Match match in regex.Matches(content))
          {
            user = match.Groups[1].ToString();
            usernames.TryAdd(user, null);
          }
          progressBar1.PerformStep();
        }
        finally
        {
          semaphore.Release();
        }
      }));
    }
    

提交回复
热议问题