Reputation: 5927
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?
Upvotes: 1
Views: 1785
Reputation: 755239
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.
Upvotes: 3
Reputation: 134055
That code won't cause any thread safety issues, provided you don't modify the SafeRules
collection while other threads are enumerating it.
Upvotes: 3