Regex实例线程对于C#中的匹配是否安全? [英] Is Regex instance thread safe for matches in C#

查看:139
本文介绍了Regex实例线程对于C#中的匹配是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Parallel.ForEach< string> 中使用了此正则表达式。安全吗?

I have this regex which I am using in a Parallel.ForEach<string>. Is it safe?

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确认了这一点

Regex objects are read-only, and therefore are thread safe. It's their returns, the Match objects that could potentially cause problems. MSDN confirms this:


Regex类本身是线程安全且不可变的(只读)。也就是说,Regex对象可以在任何线程上创建并在线程之间共享;可以从任何线程调用匹配方法,并且永远不会更改任何全局状态。

但是,返回了结果对象(Match和MatchCollection) Regex编写的应在单个线程上使用。.

我会担心您的Match集合的状态以可能是并发的方式生成的,这可能导致集合的行为有点怪异。某些Match实现使用延迟的评估,这可能会在 foreach 循环中引起疯狂的行为。我可能会收集所有比赛,然后再进行评估,以确保安全并获得一致的表现。

I'd be concerned about how your Match collection is being generated in a way that might be concurrent, which could cause the collection to act kinda weird. Some Match implementations use delayed evaluation, which could cause some crazy behavior in that foreach loop. I would probably collect all the Matches and then evaluate them later, both to be safe and to get consistent performance.

这篇关于Regex实例线程对于C#中的匹配是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆