代码之家  ›  专栏  ›  技术社区  ›  Master Morality

收益率的线程安全性(是吗?)

  •  1
  • Master Morality  · 技术社区  · 14 年前

    public class Config
    {
        public IEnumerable<Regex> GetSafeRuleRegex()
        {
            foreach (string rule in this.SafeRules)
            {
                Regex regex = null;
    
                try
                {
                    regex = new Regex(rule, RegexOptions.IgnoreCase);
                }
                catch(Exception e)
                {
                    Trace.Write(e.Message);
                }
    
                if (regex != null)
                    yield return regex;
            }
        }
    }
    
    public class Dispatcher
    {
        public void Start()
        {
            var config = new Config();
    
            for (var i = 0; i < 10; i++)
            {
                ThreadPool.QueueUserWorkItem(new WaitCallback(o => new Item(config)));
            }
        }
    }
    

    这会导致锁定问题吗?

    2 回复  |  直到 14 年前
        1
  •  3
  •   JaredPar    14 年前

    看来问题是你在打电话 Config::GetSafeRuleRegex 就一个人 Config 来自多个线程的实例,不知道这是否安全。

    yield return 在这种情况下。调用的每个线程 GetSafeRuleRegex 将获得单独的迭代器实例。在多个线程上创建它们是安全的,前提是该实例只在创建它的线程上使用。

    内部的其他代码可能有问题 GetSafeRuleRegex . 但是它取决于 配置 这些问题还不清楚。

        2
  •  3
  •   Jim Mischel    14 年前

    如果不修改 SafeRules 集合,而其他线程正在枚举它。