我有一个正则表达式,我正在Parallel.ForEach< string> ;.是否安全?
Regex reg = new Regex(SomeRegexStringWith2Groups); Parallel.ForEach<string>(MyStrings.ToArray(),(str) => { foreach (Match match in reg.Matches(str)) //is this safe? lock (dict) if (!dict.ContainsKey(match.Groups[1].Value)) dict.Add(match.Groups[1].Value,match.Groups[2].Value); });
正则表达式对象是只读的,因此是线程安全的。这是他们的回报,Match对象可能会导致问题。
MSDN confirms this:
The Regex class itself is thread safe and immutable (read-only). That is,Regex objects can be created on any thread and shared between threads; matching methods can be called from any thread and never alter any global state.
However,result objects (Match and MatchCollection) returned by Regex should be used on a single thread ..
我会担心您的Match集合的生成方式可能是并发的,这可能导致集合的行为有点奇怪。一些Match实现使用延迟评估,这可能会导致foreach循环中的一些疯狂的行为。我可能会收集所有的匹配,然后评估它们,以便安全,并获得一致的性能。