将返回一个IEnumerable<>线程安全的? [英] Is returning an IEnumerable<> thread-safe?

查看:157
本文介绍了将返回一个IEnumerable<>线程安全的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Visual Studio 2008的C#.NET 3.5的项目,我想有对象的线程安全的游泳池。

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);
            }
        }
    }
}



时在公开的IEnumerable<富> FOOS {搞定; } 函数是线程安全的?或者,是否需要克隆的结果,并返回一个新的列表?

Is the public IEnumerable<Foo> Foos { get; } function thread-safe? Or, do I need to clone the result and return a new list?

推荐答案

没有,它不是。

如果您同时主叫方列举了,你会得到一个错误,另一个线程添加到字典中。

If another thread adds to the dictionary while your caller enumerates that, you'll get an error.

相反,可以这样做:

lock (pool_lock_) {
    return foo_pool.Values.ToList();
}

这篇关于将返回一个IEnumerable&LT;&GT;线程安全的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆