views:

53

answers:

4

In C# (console app) I want to hold a collection of objects. All objects are of same type. I want to iterate through the collection calling a method on each object. And then repeat the process continuously. However during iteration objects can be added or removed from the list. (The objects themselves will not be destroyed .. just removed from the list). Not sure what would happen with a foreach loop .. or other similar method. This has to have been done 1000 times before .. can you recommend a solid approach?

A: 

This is classic case of syncronization in multithreading.

Only solid approach and better approach would be syncronization between looping and addition/deletion of items from list.

Means you should allow addition/deletion only at end of end and start of iterating loop!

some thing like this:-

    ENTER SYNC_BLOCK
      WAIT FOR SYNC_BLOCK to be available

      LOOP for items/ call method on them.

     LEAVE SYNC_BLOCK


     ENTER SYNC_BLOCK
      WAIT FOR SYNC_BLOCK to be available

     Add/Delete items

 LEAVE SYNC_BLOCK
thatsalok
A: 

Possible duplicate: http://stackoverflow.com/questions/308466/how-to-modify-or-delete-items-from-an-enumerable-collection-while-iterating-throu

Ando
While both questions deal with iterating over a list, this one specifically asks about multi-threading issues surrounding the iteration, whereas the one you mention deals with whether you can add/remove items during a for loop iteration. Two different aspects of iterating over lists in my view.
Marjan Venema
Agree with Marjan Venema. Collection iteration under multithreading scenario is completely different topic. So no duplication here
Vadmyst
+1  A: 

There is also copy based approach. The algorithm is like that:

  1. take the lock on shared collection
  2. copy all items from shared collection to some local collection
  3. release lock on shared collection
  4. Iterate over items in local collection

The advantage of this approach is that you take the lock on shared collection for small period of time (assuming that shared collection is relatively small).

In case when method that you want to invoke on every collection item takes some considerable time to complete or can block then the approach of iterating under shared lock can lead to blocking other threads that want to add/remove items from shared collection

However if that method that you want to invoke on every object is relatively fast then iterating under shared lock can be more preferable.

Vadmyst
A: 
Marcus Griep