C# 对Regex.Matches使用Parallel.ForEach的NullReferenceException
我有密码:C# 对Regex.Matches使用Parallel.ForEach的NullReferenceException,c#,parallel-processing,C#,Parallel Processing,我有密码: public void FindMatches(string source) { ... var matchCollections = new List<MatchCollection>(); Parallel.ForEach(patterns, pattern => { var regex = new Regex(pattern); MatchCollection ma
public void FindMatches(string source)
{
...
var matchCollections = new List<MatchCollection>();
Parallel.ForEach(patterns,
pattern =>
{
var regex = new Regex(pattern);
MatchCollection matches = regex.Matches(source, 0);
matchCollections.Add(matches);
}
);
foreach (MatchCollection matches in matchCollections)
{
if (matches.Count > 0) //NullReferenceException
{
foreach (Match match in matches)
{
...
}
}
}
...
}
public void find匹配(字符串源)
{
...
var matchCollections=新列表();
并行。ForEach(模式,
模式=>
{
var regex=新的regex(模式);
MatchCollection matches=regex.matches(源,0);
matchCollections.Add(匹配项);
}
);
foreach(MatchCollection中的MatchCollection匹配项)
{
if(matches.Count>0)//NullReferenceException
{
foreach(匹配中的匹配)
{
...
}
}
}
...
}
有时我会在15行中出现NullreferenceException。如果在插入到“matchCollections”之前检查“matches”是否为null,则仍然会引发异常。有什么问题吗?列表不是线程安全的。这意味着如果您从多个线程访问它,您将得到任何类型的随机错误,并且列表实例数据将被破坏。访问列表时锁定列表,或者改用线程安全集合:
或者,在您的情况下,如果您可以返回并行任务的结果,并让并行库收集结果,则效果会更好,但我不确定它是否可以这样工作。这就是我发现的:列表不是线程安全的。这意味着如果您从多个线程访问它,您将得到任何类型的随机错误,并且列表实例数据将被破坏。访问列表时锁定列表,或者改用线程安全集合:
或者,在您的情况下,如果您可以返回并行任务的结果,并让并行库收集结果,则效果会更好,但我不确定它是否可以这样工作。这就是我发现的: