簡體   English   中英

NullReferenceException對Regex.Matches使用Parallel.ForEach

[英]NullReferenceException using Parallel.ForEach for Regex.Matches

我有代碼:

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

有時我在15行中有NullreferenceException。 如果在插入“ matchCollections”之前檢查“ matches”不為null,則引發異常。 什么問題?

List <T>不是線程安全的。 這意味着,如果您從多個線程訪問它,將會得到任何類型的隨機錯誤,並且列表實例數據將被破壞。 訪問列表時鎖定列表,或使用線程安全的集合代替: http : //msdn.microsoft.com/en-us/library/dd997305%28v=vs.110%29.aspx

或者,如果您可以從並行任務中返回結果並讓並行庫收集結果,則對您而言甚至會更好,但是我不確定它是否可以那樣工作。 這是我發現的: http : //msdn.microsoft.com/en-us/library/ff963547.aspx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM