开发者

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.SafeRul开发者_如何学编程es)
        {
            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?


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜