0

Can someone suggest where someone is supposed to use the for loop instead of Parallel.For in .NET 4.0 Framework?

I have done small PoC on using for and Parallel.For on a specific long algorithm and result are quite in favour of Parallel.For even in Single Core environment.

Can we simple ignore the for loop in .NET 4.0 Framework?

Pankaj Gaur
  • 307
  • 2
  • 4
  • 17
  • When you want a loop to run sequentially instead of simultaneously? For example, if the loop modifies the collection over which it iterates. Doing that in multiple threads would be... unwise. – David Mar 15 '13 at 11:09
  • Uh, no. What you use in each case is determined by your requirements and restrictions for that code. You cannot say anything is always in programming. –  Mar 15 '13 at 11:10
  • 1
    Possible duplicate of [Usage of Parallel.For](http://stackoverflow.com/q/4635147/109702) or [When to use Parallel.For?](http://stackoverflow.com/q/3715850/109702), and that was the [first page](http://stackoverflow.com/search?q=parallel.for) of the results... – slugster Mar 15 '13 at 11:13
  • Thanks slugster for your suggestion. I had already gone through that and after then only I have posted my question as I was really looking some more points as best explained below by Mark in the below answer – Pankaj Gaur Mar 15 '13 at 13:08

1 Answers1

4

There are lots of factors to consider here:

  • is the code inside the loop written to support concurrent access? is it thread safe? if not: that's a huge problem
  • if all the threads would end up immediately needing didicated / synchronized access to a single resource (such as the UI), then there is nothing to gain from concurrency
  • what else is happening on this machine? if this is a web server, it may be better not for one request to hijack lots of cores
  • but conversely, if this is a client-side application, then sure: use lots of cores and ideally free up the UI thread ASAP
  • is the work CPU bound? IO bound? what? Parallel access to a single disk spindle can make things worse, not better
  • threading has overhead; concurrency increases the total work done - with the intent of reducing the elapsed time
  • is it done locally, or on a different server? if so, what is the threading model of that other server?

In most cases, for / foreach is fine.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900