tags:

views:

2096

answers:

4

I'm looking for a way of getting a concurrent collection in C# or at least a collection which supports a concurrent enumerator. Right now I'm getting an InvalidOperationException when the collection over which I'm iterating changes. I could just deep copy the collection and work with a private copy but I'm wondering if there is perhaps a better way

Code snippet:

foreach (String s in (List<String> )callingForm.Invoke(callingForm.delegateGetKillStrings))
    {
        //do some jazz
    }

--edit--

I took the answer but also found that I needed to ensure that the code which was writing to the collection needed to attempt to get a lock as well.

 private void addKillString(String s)
 {
  lock (killStrings)
  {
   killStrings.Add(s);
  }
 }
+3  A: 

Other than doing a deep-copy your best bet might be to lock the collection:

   List<string> theList = (List<String> )callingForm.Invoke(callingForm.delegateGetKillStrings);
    lock(theList.SyncRoot) {
        foreach(string s in theList) {
               // Do some Jazz
        }
    }
Damian Mehers
+4  A: 

So I'm not quite sure what you're asking, but the Parallel Extensions team has put together some stuff that might fit the bill. See this blog post in particular, about enumerating parallel collections. It also contains a link to download the Parallel CTP, and you can of course browse through the rest of the blog posts to get an idea of what the CTP is meant to do and how the programming model works.

Domenic
+1  A: 

If you want to use the FCL collections, then locking is the only way to support iteration / modification from multiple threads that may overlap.

Be careful what you use as your lock object, though. Using SyncRoot is only a good idea if the collection itself is a private member of the class that uses it. If the collection is protected or public, then a client of your class can take its own lock on your SyncRoot, potentially deadlocking with code in your class.

If you are interested in taking a look at a 3rd-party collection library, I recommend the excellent C5 Generic Collection Library. They have a family of tree-based collections that can easily and safely be modified and iterated at the same time without locking - see sections 8.10 and 9.11 of their (excellent) documentation for details.

McKenzieG1
A: 

Concurrent collection in C# .net

http://www.codeproject.com/KB/cs/MultiMap_P_2.aspx