Hi,
I'm having issues with concurrent usage of a shared collection with a multi-player synchronous game I'm working on. I did some digging around and found a neat thread-safe IEnumerator/IList implementation on Alexey Drobyshevsky's post on codeproject here:
http://www.codeproject.com/KB/cs/safe_enumerable.aspx
After adopting his implementation I have even replaced all Linq queries on the shared collection with for/foreach loops because the Linq queries were still using the unsafe IEnumerable underneath.
Here's my implementation of the SafeList, and the list itself is being exposed to as a ReadOnlyCollection to the consuming classes.
http://theburningmonk.com/2010/03/thread-safe-enumeration-in-csharp/
After switching to this SafeList I am seeing far less problems, but under heavy load (80+ threads all of which read/write from and to the list at different points) I'm still seeing InvalidOperationException being thrown:
The element list has changed. The enumeration operation failed to continue
I have even tried using ReadWriterLockSlim in place of the lock object in my implementation of the SafeList but that proved fruitless too. The only other suggestion I have had so far is cloning the list every time a threads needs to loop through it. I'm hoping to avoid cloning the list every single time as the list is being used in way too many places it might be a performance hit and might introduce other bugs that are difficult to spot.
Given the time constraints I'll have to be pragmatic about it and if cloning is the safest and quickest way to go about solving this problem then I'm fine with it, but before resorting to this last ditch-attempt I'm just wondering if anyone out there has come across something similar is able to offer some advice.
Many thanks in advance!
[EDIT] Here is a little more information about the problem I'm seeing as requested:
For one 'game', there can be up to 100 or so synchronous clients connected and the game needs to message each connected client with updates every few seconds and so every few seconds this game needs to iterate through the shared list of players. When a player joins, or leaves, the list needs to be updated accordingly to reflect the changes. To add to that, the players can interact with the game and chat to other players, and every time a message is received from the player the game would again need to iterate through the same list and do a broadcast. The exceptions are typically thrown when the game is trying to broadcast messages to players (read operation) at the same time as many players leaving/joining (write operation) at the same time.