user1789782
user1789782

Reputation: 197

C# multithread concurrency algorithm

I have a list of object that's in a List. This list could have as little and one or as much as 500 entries. I also have a thread that takes this list as processes these objects in a sequential manner.

To speed things up I need to split this list into multiple threads for concurrent processing and at the same time control how many threads are running at the same time.

What is the best way to split this list and pass the smaller lists to threads for concurrent processing and control the total amount of active threads?

Upvotes: 2

Views: 612

Answers (1)

Snak
Snak

Reputation: 693

Sounds like a perfect case to use a parallel foreach loop.

By definition :

The parallel ForEach loop provides a parallel version of the standard, sequential foreach loop. Each iteration processes a single item from a collection. However, the parallel nature of the loop means that multiple iterations may be executing at the same time on different processors or processor cores. This opens up the possibility of synchronisation problems so the loop is ideally suited to processes where each iteration is independent of the others.

Take a look at .NET documentation about Parallel.ForEach and some examples in order to understand how it works.

Upvotes: 1

Related Questions