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?
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
Possible duplicate: http://stackoverflow.com/questions/308466/how-to-modify-or-delete-items-from-an-enumerable-collection-while-iterating-throu
There is also copy based approach. The algorithm is like that:
- take the lock on shared collection
- copy all items from shared collection to some local collection
- release lock on shared collection
- 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.