Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9230835
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T05:55:00+00:00 2026-06-18T05:55:00+00:00

How do I turn the following into a Parallel.ForEach? public async void getThreadContents(String[] threads)

  • 0

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

public async void getThreadContents(String[] threads)
{
    HttpClient client = new HttpClient();
    List<String> usernames = new List<String>();
    int i = 0;

    foreach (String url in threads)
    {
        i++;
        progressLabel.Text = "Scanning thread " + i.ToString() + "/" + threads.Count<String>();
        HttpResponseMessage response = await client.GetAsync(url);
        String content = await response.Content.ReadAsStringAsync();
        String user;
        Predicate<String> 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());
            }
        }
        progressBar1.PerformStep();
    }
}

I coded it in the assumption that asynchronous and parallel processing would be the same, and I just realized it isn’t. I took a look at all the questions I could find on this, and I really can’t seem to find an example that does it for me. Most of them lack readable variable names. Using single-letter variable names which don’t explain what they contain is a horrible way to state an example.

I normally have between 300 and 2000 entries in the array named threads (Contains URL’s to forum threads) and it would seem that parallel processing (Due to the many HTTP requests) would speed up the execution).

Do I have to remove all the asynchrony (I got nothing async outside the foreach, only variable definitions) before I can use Parallel.ForEach? How should I go about doing this? Can I do this without blocking the main thread?

I am using .NET 4.5 by the way.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T05:55:01+00:00Added an answer on June 18, 2026 at 5:55 am

    I coded it in the assumption that asynchronous and parallel processing would be the same

    Asynchronous processing and parallel processing are quite different. If you don’t understand the difference, I think you should first read more about it (for example what is the relation between Asynchronous and parallel programming in c#?).

    Now, what you want to do is actually not that simple, because you want to process a big collection asynchronously, with a specific degree of parallelism (8). With synchronous processing, you could use Parallel.ForEach() (along with ParallelOptions to configure the degree of parallelism), but there is no simple alternative that would work with async.

    In your code, this is complicated by the fact that you expect everything to execute on the UI thread. (Though ideally, you shouldn’t access the UI directly from your computation. Instead, you should use IProgress, which would mean the code no longer has to execute on the UI thread.)

    Probably the best way to do this in .Net 4.5 is to use TPL Dataflow. Its ActionBlock does exactly what you want, but it can be quite verbose (because it’s more flexible than what you need). So it makes sense to create a helper method:

    public static Task AsyncParallelForEach<T>(
        IEnumerable<T> source, Func<T, Task> body,
        int maxDegreeOfParallelism = DataflowBlockOptions.Unbounded,
        TaskScheduler scheduler = null)
    {
        var options = new ExecutionDataflowBlockOptions
        {
            MaxDegreeOfParallelism = maxDegreeOfParallelism
        };
        if (scheduler != null)
            options.TaskScheduler = scheduler;
    
        var block = new ActionBlock<T>(body, options);
    
        foreach (var item in source)
            block.Post(item);
    
        block.Complete();
        return block.Completion;
    }
    

    In your case, you would use it like this:

    await AsyncParallelForEach(
        threads, async url => await DownloadUrl(url), 8,
        TaskScheduler.FromCurrentSynchronizationContext());
    

    Here, DownloadUrl() is an async Task method that processes a single URL (the body of your loop), 8 is the degree of parallelism (probably shouldn’t be a literal constant in real code) and FromCurrentSynchronizationContext() makes sure the code executes on the UI thread.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I use the following to take an array called $list and turn it into
The following link explains how to turn a date range into a list of
What is the best way to turn the following Ruby String into an Array
I have the following statement, I want to turn it into a Public Shared
I'm trying to turn a string into a char list list and I have
How can I turn the following list ['1','2','A,B,C,D','7','8'] into ['1','2','A','B','C','D','7','8'] in the most pythonic
I have the following ungainly code to turn a date string into another date
Possible Duplicate: Taking .get json string, turn into array? Im using the following to
so my code I want to turn into JSON is the following var locationData
I have the following array, $myarray[0]['first_name'] $myarray[0]['last_name'] I want to turn it into: $myarray['first_name']

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.