我有一個concurrentbag集合,我添加項目太..現在我可能最終會超過一個項目是相同的(由3個字符串屬性相等定義)ConcurrentBag不同
我不知道兩件事情。
- 如何生成的哈希碼出3個屬性
- 如果concurrengbag轉換到列表然後使用自定義的衍生比較器做一個明顯的上它是正確的方式..
的基本上目標是有可能包含重複然後在addcities方法cityProcessor財產NotFoundCities只能獲得非的DUP
public class CityProcesor
{
public ConcurrentBag<CityNotFound> NotFoundCities { get; set; }
public void AddCities()
{
var nonDups = NotFoundCities.ToList().Distinct(new NotFoundCityComparer());
}
}
public class CityNotFound
{
public string Name { get; set; }
public string RegionName { get; set; }
public string CountryCode { get; set; }
}
public class NotFoundCityComparer : IEqualityComparer<CityNotFound>
{
public bool Equals(CityNotFound city1, CityNotFound city2)
{
return city1.Name == city2.Name && city1.RegionName == city2.RegionName && city1.CountryCode == city2.CountryCode;
}
public int GetHashCode(CityNotFound obj)
{
return 1; //TODO: fix
}
}
ConcurrentBag是一個非常特殊的集合,它使用線程本地存儲來確保每個線程快速訪問它創建的值。它不是HashSet的併發版本。你確定這是你想要的嗎? – 2014-10-06 15:07:27
使用concurrentbag的原因是因爲多個線程正在添加到相同的集合 – Zoinky 2014-10-06 15:08:30
正如我所說,這不是*它應該用於什麼。當您在ConcurrentBag上執行'ToList()'時,您將快速獲得調用線程創建的項目並等待其他項目。您可以使用ConcurrentDictionary或甚至是ConcurrentQueue來描述您所描述的場景。你必須在這兩種情況下重寫'GetHashCode' – 2014-10-06 15:11:36