I am looking at Skeet’s AtomicEnumerable but I’m not sure how to integrate it into my current IEnumerable exmaple below (http://msmvps.com/blogs/jon_skeet/archive/2009/10/23/iterating-atomically.aspx)
Basically I want to foreach my blahs type in a thread-safe way.
thanks
so .. foreach on multiple threads … giving correct order
Blahs b = new Blahs();
foreach (string s in b)
{ }
public sealed class Blahs : IEnumerable<string>
{
private readonly IList<string> _data = new List<string>() { "blah1", "blah2", "blah3" };
public IEnumerator<string> GetEnumerator()
{
return _data.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
Do you mean you want each thread to see the same sequence, or that between all the threads, each item should be seen exactly once?
Are you able to use .NET 4? If so, Parallel Extensions (e.g.
Parallel.ForEach) is your friend – it’s likely to be much safer than anything I could come up with 🙂EDIT: If you want to just iterate over the list completely in each thread, and nothing is going to be modifying the list, it will be thread-safe already. If you do need to modify the list, then you should create a copy of the list and iterate over that instead.