我有一个 Visual Studio 2008 C# .NET 3.5 项目,我想要一个线程安全的Foo
对象池。
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);
}
}
}
}
函数是public IEnumerable<Foo> Foos { get; }
线程安全的吗?或者,我是否需要克隆结果并返回一个新列表?