Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run any number of functions, each on their own thread

What is the most efficient way of performing the same function on a collection of objects, each running in parallel? I know I could just do new Thread(() => MyFunc(myParam)).Start() in a loop, but is there a better way? This seems like a very ugly way of doing it.

like image 658
Rogue Avatar asked Dec 25 '22 18:12

Rogue


2 Answers

[...] is there a better way? This seems like a very ugly way of doing it.

Yes, that is a very ugly and inefficient way of doing it. Each thread will consume a lot of resources but your computer can only execute N threads at the same time where N is the number of CPU cores on your computer. So instead of using a low-level primitive like a thread you can build on top of libraries that optimize the number of threads to fit the number of CPU cores.

In your case where you have a collection of objects I suggest:

  • Parallel LINQ
  • Parallel.ForEach
  • Parallel.For

LINQ code:

var result = source.Select(item => ...).ToList();

Parallel LINQ code:

var result = source.AsParallel().Select(item => ...).ToList();

For each loop:

foreach (var item in source)
  Process(item);

Parallel for each loop:

Parallel.ForEach(
  source,
  item => Process(item);
);

For loop:

for (var i = 0; i < list.Count; i += 1)
  list[i] = Process(list[i]);

Parallel for loop:

Parallel.For(
  0,
  list.Count,
  i => {
    list[i] = Process(list[i]);
  }
);
like image 186
Martin Liversage Avatar answered Dec 27 '22 06:12

Martin Liversage


You can use Parallel.For or Parallel.Foreach or Parallel.Invoke starting from .net 4.0.

There is very little reason to use Thread directly in your code starting from .Net4.0. You can use TPL which is recommended way of achieving Task parallelism or Data parallelism.

To quote Stephen Cleary from his book

As soon as you type new Thread(), it’s over; your project already has legacy code

like image 42
Sriram Sakthivel Avatar answered Dec 27 '22 08:12

Sriram Sakthivel