线程安全的产量回报(是吗?) [英] Thread Safety of yield return (is it?)

查看:131
本文介绍了线程安全的产量回报(是吗?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个类的共享实例在不同的线程上的其他2个类之间共享。让我解释一下:

So I have a common instance of a class shared between 2 other classes on different threads. let me explain:

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

这会导致锁定问题吗?

will this cause locking issues?

推荐答案

看来这里的问题是你正在调用 Config :: GetSafeRuleRegex 在多个线程的单个配置实例,并想知道这是否安全。

It appears the question here is that you are calling Config::GetSafeRuleRegex on a single Config instance from multiple threads and are wondering if this is safe.

在这种情况下, yield return 没有任何固有的危险。每个调用 GetSafeRuleRegex 的线程将获得一个单独的迭代器实例。在多个线程上创建它们是安全的,只要实例只在创建的线程上使用。

There is nothing inherently dangerous about yield return in this scenario. Each thread which calls GetSafeRuleRegex will get a separate iterator instance. It's safe to create them on multiple threads provided the instance is only used on the thread it's created on.

GetSafeRuleRegex 中的其他代码可能存在一些问题。但是它依赖于这个问题不清楚的 Config 的实现细节。

There could be some issues with the other code within GetSafeRuleRegex. However it's dependent on implementation details of Config that aren't clear from this questions.

这篇关于线程安全的产量回报(是吗?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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