Run async method 8 times in parallel

前端 未结 4 1162
再見小時候
再見小時候 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:46

    You can try the ParallelForEachAsync extension method from AsyncEnumerator NuGet Package:

    using System.Collections.Async;
    
    public async void getThreadContents(String[] threads)
    {
        HttpClient client = new HttpClient();
        List usernames = new List();
        int i = 0;
    
        await threads.ParallelForEachAsync(async url =>
        {
            i++;
            progressLabel.Text = "Scanning thread " + i.ToString() + "/" + threads.Count();
            HttpResponseMessage response = await client.GetAsync(url);
            String content = await response.Content.ReadAsStringAsync();
            String user;
            Predicate userPredicate;
            foreach (Match match in regex.Matches(content))
            {
                user = match.Groups[1].ToString();
                userPredicate = (String x) => x == user;
                if (usernames.Find(userPredicate) != user)
                {
                    usernames.Add(match.Groups[1].ToString());
                }
            }
    
            // THIS CALL MUST BE THREAD-SAFE!
            progressBar1.PerformStep();
        },
        maxDegreeOfParallelism: 8);
    }
    

提交回复
热议问题