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?
Dictionary
, like most .net classes isn't threadsafe. In particular it doesn't allow somebody to read and write at the same time. – OfficerFoos
function. Which is already an inherent weakness of this code. Is there a scenario where you get something worse than stale data? (i.e one thread tries to get; while another does a set;, the getter may get old data because the set; thread hasn't finished yet.) – Protractor