I\'m storing a dataset in an ASP.Net WebApplication-Cache. Every user in this intranet-app uses the same instance. On insert/update/delete-actions the database will be updat
Generally, when enumerating over a sequence, you cannot perform operations that will modify the sequence.
Because youa re storing the collection in the WebApplication cache, it can be hit by multiple threads at the same time; you might have a request on one thread enter an item in the cache while another is trying to enumerate over it.
To combat this, you really should make access to the data structure thread-safe.
You have a few options for this. The first, and easiest, would be to encapsulate access to the sequence in a lock
block. You have to wrap add/edit/delete operations in individual blocks, and you also have target the same object in a lock
block over the enumeration of the entire sequence.
This can easily be encapsulated in another class and then you store that in your cache.
If you are also performing a high number of read operations compared to write operations, then you can use the ReaderWriterLockSlim class to lock reads and writes appropriately; the strategy above will lock two concurrent reads out.
Another solution would be to lock around any add/edit/update operation on the cache, and when you want to enumerate the cache, lock and create a copy of the sequence itself and return that; once you return the copy of the sequence, you can enumerate that separately as that sequence is different from the one you are actually modifying.