简体   繁体   中英

Parallel.For/Foreach loop take elements outside of a list in synchronized order

I have a parallel for loop and a list which looks like this:

 var itemsList = new List<string> { "1","2","3","4","5","6","7","8","9","10","11" };

 Parallel.For(0, 5000, ex=>
 {

 });

What I would like to do here:

  • Take out elements from itemsList one by one in exact order as they are in the list, regardless of the parallel iteration being called randomly

So basically in first random parallel operation item under "1" value would be stored in the first variable like following:

var itemFromList = itemList.elementAt(0).Take(1);

In second iteration of parallel foreach/for loop:

var itemFromList = itemList.elementAt(1).Take(1);

Once all 11 items from the list have been used.. I'd just like to repeat this process once allover again.

Then again if the last item that was stored into the variable:

var itemFromList = itemList.elementAt(10).Take(1); // Last item

And then again first item from the list is used again:

var itemFromList = itemList.elementAt(0).Take(1);

Iteration repeats like this indefinitely.

Can someone help me out with this one ?

This will execute on all elements the same amount of times.
And as long as you only read from the list it should be thread-safe.

But 'sequential in time' is not compatible with going Parallel.

 Parallel.For(0, 5000, ex=>
 {
    int myIndex = ex % itemsList.Count;
    string myItem = itemsList[myIndex];
    // use myItem
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM