C#线程安全的收益率返回值安全吗? [英] Is yield return in C# thread-safe?

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

问题描述

我有以下代码:

private Dictionary<object, object> items = new Dictionary<object, object>;
public IEnumerable<object> Keys
{
    get
    {
        foreach (object key in items.Keys)
        {
            yield return key;
        }
    }
}

这是线程安全的吗?如果不是,我必须在循环或yield return周围放一个lock?

Is this thread-safe? If not do I have to put a lock around the loop or the yield return?

这是我的意思:

Thread1访问Keys属性,而Thread2将项添加到基础字典中. Thread1是否受Thread2的添加影响?

Thread1 accesses the Keys property while Thread2 adds an item to the underlying dictionary. Is Thread1 affected by the add of Thread2?

推荐答案

好的,我做了一些测试,结果很有趣.

OK, I did some testing and got an interesting result.

似乎与yield关键字相比,更多的是基础集合的枚举器问题.枚举器(实际上是其MoveNext方法)会抛出(如果正确实现)InvalidOperationException,因为枚举已更改.根据 MoveNext方法的MSDN文档这是预期的行为.

It seems that it is more an issue of the enumerator of the underlying collection than the yield keyword. The enumerator (actually its MoveNext method) throws (if implemented correctly) an InvalidOperationException because the enumeration has changed. According to the MSDN documentation of the MoveNext method this is the expected behavior.

因为通过集合进行枚举通常不是线程安全的,所以yield return也不是线程安全的.

Because enumerating through a collection is usually not thread-safe a yield return is not either.

这篇关于C#线程安全的收益率返回值安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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