简体   繁体   中英

Thread Safety of yield return (is it?)

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?

该代码不会引起任何线程安全问题,只要您在其他线程枚举时不修改SafeRules集合即可。

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM