Run any number of functions, each in its own thread

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

+4
source share
2 answers

[...] is there a better way? This seems like a very ugly way to do it.

Yes, this is a very ugly and inefficient way to do this. Each thread will consume a lot of resources, but your computer can only execute N threads at a time, where N is the number of processor cores on your computer. Therefore, instead of using a low-level primitive, such as a thread, you can create on top of libraries that optimize the number of threads to match the number of processor cores.

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

LINQ Code:

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

LINQ parallel code:

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

For each cycle:

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

In parallel for each cycle:

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

For the loop:

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

Parallel loop:

Parallel.For(
  0,
  list.Count,
  i => {
    list[i] = Process(list[i]);
  }
);
+8
source

You can use Parallel.Foreither Parallel.Foreachor Parallel.Invoke, starting with .net 4.0.

Thread , .Net4.0. TPL, parallelism parallelism.

new Thread(), ;

+2

All Articles