Is returning an IEnumerable<> thread-safe?
.net-3.5, c#, thread-safety
Solution
No, it isn't.
If another thread adds to the dictionary while your caller enumerates that, you'll get an error.
Instead, you can do:
lock (pool_lock_) {
return foo_pool.Values.ToList();
}
Problem
I have a Visual Studio 2008 C# .NET 3.5 project where I want to have a thread-safe pool of `Foo` objects. ``` public class FooPool { private object pool_lock_ = new object(); private Dictionary<int, Foo> foo_pool_ = new Dictionary<int, Foo>(); // ... public void Add(Foo f) { lock (pool_lock_) { foo_pool_.Add(SomeFooDescriminator, f); } } public Foo this[string key] { get { return foo_pool_[key]; } set { lock (pool_lock_) { foo_pool_[key] = value; } } } public IEnumerable<Foo> Foos { get { lock (pool_lock_) { // is this thread-safe? return foo_pool_.Select(x => x.Value); } } } } ``` Is the `public IEnumerable<Foo> Foos { get; }` function thread-safe? Or, do I need to clone the result and return a new list?