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.
[...] 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.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]);
}
);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With