Askcomp eugi-tech
Askcomp eugi-tech

Reputation: 83

Enumerating updated lists

How can I enumerate throw updating lists. For example, I have the following code:

For I as integer = 0 to MyList.Count-1
.......
.......
Next

when I run this loop the (MyList) is updated from Another source, then I will get an error "Collection was modified."

I don't want to stop the update of the (MyList), and also I need an instance of the list separated from the updated one. For example: if the (MyList) contains 10 items before I start the For...Next loop and throw the loop the (MyList) updated from outer source to be 12 items, I steel need to run the For....Next for the 10 items only and I don't want the extra new 2 items. and at the same time I don't want to lose these new 2 items.

I decided to have a copy from (MyList) by the following code:

 m.ToList.AsEnumerable

because (MyList) is 'iEnumerable(Of DataRow)', but also I've gotten the same error "Collection was modified"

Any Idea??

Upvotes: 0

Views: 64

Answers (1)

germi
germi

Reputation: 4658

If you need to enumerate the list while other threads might be changing it, one option is to just copy it (in C#, as I'm not fluent in VB):

var list = new List<int>(MyList);
for(int i = 0; i < list.Count; i++)
{
    // process your original items 
    // regardless of whether someone adds or removes from 'MyList'
}

Upvotes: 1

Related Questions