Maxim Tkachenko
Maxim Tkachenko

Reputation: 5798

NullReferenceException using Parallel.ForEach for Regex.Matches

I have code:

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)
         {
            ...
         }
      }
   } 
   ...
}

Sometimes I've got NullreferenceException in 15 line. In case of checking "matches" not null before inserting to "matchCollections" - exception is thrown all the same. What's problem?

Upvotes: 0

Views: 3927

Answers (1)

fejesjoco
fejesjoco

Reputation: 11903

The List<T> is not thread-safe. It means that if you access it from multiple threads, you will get any kind of random errors, and the list instance data will be corrupted. Either lock the list when you access it or use a thread-safe collection instead: Thread-safe collections.

Or it would be even better in your case, if you could return the result from the parallel task and let the parallel library collect results, but I'm not sure it works like that. This is what I found: Parallel Aggregation.

Upvotes: 5

Related Questions