Reputation: 2189
I have this Parallel.For code:
foreach (string g in allGames)
{
eventsList.Add(game);
}
eventsList.Distinct();
Parallel.For(0, eventsList.Count, i =>
{
Console.WriteLine(eventsList[i]);
});
The allGames array contains the following strings:
String A: Lee, Stephen - Cope, Jamie
String B: Carter, Ali - Stevens, M
String C: Dott, G - McManus, Alan
String D: Bingham, S - Liu Song
String E: Davis, Mark - Joyce, Mark
String F: Walden, R - Liu Chuang
My result looks like:
Game: Lee, Stephen - Cope, Jamie
Game: Lee, Stephen - Cope, Jamie
Game: Lee, Stephen - Cope, Jamie
Game: Lee, Stephen - Cope, Jamie
Game: Carter, Ali - Stevens, M
Game: Dott, G - McManus, Alan
Game: Bingham, S - Liu Song
Game: Davis, Mark - Joyce, Mark
Game: Walden, R - Liu Chuang
It seems like it goes on same iteration for 4 times (it happens many times in the code).
I confirmed that the eventsList list DOES NOT contain any duplicates, thats 100% confirmed.
Any clue how can I solve this issue to make it works only once on each element?
Thanks!
Upvotes: 1
Views: 271
Reputation: 1500535
This may be the problem - or at least it's a bug in your code:
eventsList.Distinct();
That doesn't do anything - like all other LINQ operators, it returns a new sequence, rather than modifying the existing one. Try:
eventsList = eventsList.Distinct().ToList();
I know you say you're 100% sure that the list doesn't contain any duplicates - but in that case you wouldn't need the distinct call, would you? Either way, it was a useless line of code.
The Parallel.For
code you've given is fine, although it would be neater with Parallel.ForEach
:
Parallel.ForEach(eventsList, Console.WriteLine);
If that still fails, please post a short but complete program demonstrating the problem.
Upvotes: 4