Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Starting tasks in a dynamic way

I have a List<someObject> and an extention method to someObject called Process.

Consider the following

private void processList(List<someObject> list)
{
  Task.Factory.StartNew(() =>{
    foreach(var instance in list)
    {
        instance.Process();
    }});
}

but I wanted multiple Tasks to work on the same list, to avoid locking I cloned the list and divided it into 2 lists, then started 2 separate Tasks to process, the speed has almost doubled.

I was wondering if there are built in things in .NET that could help me achieve such things in a dynamic way and with cleaner syntax?

like image 468
FPGA Avatar asked Dec 11 '13 18:12

FPGA


1 Answers

You can use TPL's Parallel.Foreach method

var list = new List<SomeClass>();
Parallel.ForEach(list, instance =>
{
    instance.Process();
});
like image 61
L.B Avatar answered Nov 01 '22 09:11

L.B