加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

正则表达式实例线程对于C#中的匹配是安全的

发布时间:2020-12-14 06:33:12 所属栏目:百科 来源:网络整理
导读:我有一个正则表达式,我正在Parallel.ForEach stringgt ;.是否安全? Regex reg = new Regex(SomeRegexStringWith2Groups);Parallel.ForEachstring(MyStrings.ToArray(),(str) ={ foreach (Match match in reg.Matches(str)) //is this safe? lock (dict) if
我有一个正则表达式,我正在Parallel.ForEach< string&gt ;.是否安全?
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循环中的一些疯狂的行为。我可能会收集所有的匹配,然后评估它们,以便安全,并获得一致的性能。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读