1

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?

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
Master Morality
  • 5,837
  • 6
  • 31
  • 43
  • What is this.SafeRules? Collection? Is it modified? – Aaron McIver Nov 11 '10 at 18:17
  • Without knowing what `Item` does with `config` or the rest of `Config` it is impossible to tell if that will cause "locking issues". What are locking issues anyway? – MSN Nov 11 '10 at 18:19
  • I should have said race conditions. my bad. @Aaron : Safe rules isn't modified often, they sit in a config file. I'm new to threading so I was unsure about storing a list of Regexs and using those, but I need to make sure the user passed in a valid regex, so the app doesn't blow up. – Master Morality Nov 12 '10 at 14:50

2 Answers2

3

That code won't cause any thread safety issues, provided you don't modify the SafeRules collection while other threads are enumerating it.

Jim Mischel
  • 131,090
  • 20
  • 188
  • 351
3

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.

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • Thanks! the separate iterator instance was what I was looking for. If I `lock{}` the safe rules to edit the collection, would it break any iterators, or would it I need to do something ala `this.SafeRules.ToArray()` before I iterated? – Master Morality Nov 12 '10 at 14:56