Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 对Regex.Matches使用Parallel.ForEach的NullReferenceException_C#_Parallel Processing - Fatal编程技术网

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,则仍然会引发异常。有什么问题吗?

列表不是线程安全的。这意味着如果您从多个线程访问它,您将得到任何类型的随机错误,并且列表实例数据将被破坏。访问列表时锁定列表,或者改用线程安全集合:

或者,在您的情况下,如果您可以返回并行任务的结果,并让并行库收集结果,则效果会更好,但我不确定它是否可以这样工作。这就是我发现的:

列表不是线程安全的。这意味着如果您从多个线程访问它,您将得到任何类型的随机错误,并且列表实例数据将被破坏。访问列表时锁定列表,或者改用线程安全集合:

或者,在您的情况下,如果您可以返回并行任务的结果,并让并行库收集结果,则效果会更好,但我不确定它是否可以这样工作。这就是我发现的: