4

I have a background worker which invokes parallel threads for list items

 doWork()
    {
    Parallel.foreach(list1, a=>
    {
       while(true)
       {
             //do some operations
       }
    });

    Parallel.foreach(list2, b=>
    {
        while(true)
        {
            //do some operations
        } 
    });
    }

If i want to run both of these lists together parallelly, should i create another thread as their parent or anyother way?? i am getting both the lists separately so combining them is not an option.And i am running infinite loops inside both of them.

Dave New
  • 38,496
  • 59
  • 215
  • 394
varun257
  • 296
  • 2
  • 17
  • 5
    Create two tasks and then `Task.WaitAll` – L.B Nov 13 '12 at 08:03
  • `Action action = (object obj) => { //put the parallel.foreach here };` and another action for the second `parallel.foreach` and then run the tasks and call for `Task.WaitAll` rt?? – varun257 Nov 13 '12 at 08:08

2 Answers2

5

You can use tasks to run the two loops on separate threads. Use normal foreach loops.

var t1 = Task.Factory.StartNew(() => 
{
    foreach(var a in list1)
    {
        //do some operations
    }
});

var t2 = Task.Factory.StartNew(() => 
{
    foreach(var a in list1)
    {
        //do some operations
    }
});

// This will block the thread until both tasks have completed
Task.WaitAll(t1, t2);
Dave New
  • 38,496
  • 59
  • 215
  • 394
0

Create two seperate threads for the two 'foreach' loops.

CRoshanLG
  • 498
  • 1
  • 8
  • 20