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 935525
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T21:10:11+00:00 2026-05-15T21:10:11+00:00

I am new to C#, Parallel.ForEach , and .NET in general. I want to

  • 0

I am new to C#, Parallel.ForEach, and .NET in general. I want to parallelize a search that involves thousands of locations. For each location, I compute great circle distance. That is a calculation I want to spread to different cores. My question is how do I do this if I only have one thread-local variable, as in this MSDN TPL example? For the result, I looked at Interlocked, and saw its options Add, CompareExchange, Decrement, Exchange, Increment and Read, but I’m not just adding, incrementing, decrementing, or testing for equality. I want to return the object, over several threads running in parallel, that has the shortest overall distance. My gut says this should be easy, that I should be able to create some little object that wraps a Location and a distance, but how do I capture the best answer from each thread and then choose the shortest distance among them? Here is the non-parallel version:

Location findClosestLocation(Location myLocation, List<Location> allLocations)
{
  double closest = double.MaxValue;
  Location closestLoc = null;
  foreach (Location aLoc in allLocations)
  {
    if (aLoc != myLocation)
    {
      double d = greatCircle(myLocation, aLoc);
      if (d < closest)
      {
        closest = d;
        closestLoc = aLoc;
      }
    }
  }
  return closestLoc;
}

I did see a DDJ Blog Post that seemed to offer good advice, but I wondered if it was the best advice. I see the author looping over arrays, and wonder if there isn’t a more functional way of doing this. In the functional world I would use map, lambda and min.

  • 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-05-15T21:10:11+00:00Added an answer on May 15, 2026 at 9:10 pm

    The easiest option here would be to switch to PLINQ:

    Location findClosestLocation(Location myLocation, List<Location> allLocations)
    {
         return allLocations
                   .AsParallel()
                   .Min(location => greatCircle(myLocation, location));
    }
    

    That being said, this is basically just aggregation with parallel constructs. You have a couple of options if you want to stick to the Parallel class. One option would be to synchronize this yourself within the block, using locking. I wouldn’t recommend this, as it will hurt your overall performance.

    The better option is to use the Parallel.ForEach methods which provide for local state. They would allow you to rewrite this as:

    Location findClosestLocation(Location myLocation, List<Location> allLocations)
    {
      double closest = double.MaxValue;
      Location closestLoc = null;
      object sync = new object();
    
      Parallel.ForEach<Location, Tuple<double,Location>(
          allLocations,
          () => new Tuple(double.MaxValue, null),
          (location, loopState, localState) =>
          {
              double d = greatCircle(myLocation, aLoc);
              if (d < localState.Item1)
                  return new Tuple(d, aLoc);
              else
                  return localState;
          },
          localState =>
          {
              lock(sync)
              {
                  if (localState.Item1 < closest)
                  {
                      closest = localState.Item1;
                      closestLoc = localState.Item2;
                  }
              }
          }
      );
      return closestLoc;
    }
    

    I cover using local state for aggregations in detail on my blog. This basically changes the operation to one lock operation per thread instead of one lock per processing element, so you get much higher throughput than a naive locking solution.

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

Sidebar

Related Questions

I have a Parallel foreach function that creates a new instance of a class,
I understand that the new TPL (Task Parallel Library) has implemented the Parallel.ForEach such
I have the following code: Parallel.ForEach(this.listView2.CheckedItems, new ParallelOptions { MaxDegreeOfParallelism = 4 }, (CheckedItem)
Given this code: var arrayStrings = new string[1000]; Parallel.ForEach<string>(arrayStrings, someString => { DoSomething(someString); });
I work with new Parallel.For that creates multiple threads to perform the same operation.
While I was using Parallel.ForEach in my program, I found that some threads never
Inside a Parallel Foreach I'm calling a service that gives me all information about
How do I pass 2 lists into Parallel.ForEach ? Example: List<Person> a = new
Here is the code List<string> something = new List<string>(); Parallel.ForEach(anotherList, r => { ..
How Can I Define Counter Inside Parallel.Foreach And Stop That Loot In A Specific

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.