Reputation: 47
new to Parallel processing. I'm having the issue where I have a parallel for loop calling a method to get data. However, it seems that the data is getting mixed up upon the return. It could be the code but everything I've tried in debugging looks okay.
Parallel For:
Parallel.For(0, LeagueParticipantsList.Count, n => {
if (!LeagueParticipantsList[n].ToString().Equals("")) {
//Other non important code here
History = Scanning.GoogleConnection.LogCheck(LeagueParticipantsList[n].ToString());
//Other non important code here
});
Method it's calling:
public static List<ClanHistoryData> LogCheck(String clashID) {
List<ClanHistoryData> Results = new List<ClanHistoryData>();
var clansMap = json["log"];
DateTime curDTp90 = DateTime.Now;
curDTp90 = curDTp90.AddDays(-90);
foreach (var item in clansMap) {
if (item["type"].ToString().Equals("SEEN")) {
string tempDate = item["date"].ToString();
DateTime dateStuff = DateTime.Parse(tempDate);
if (DateTime.Compare(dateStuff, curDTp90) > 0) {
Results.Add(new ClanHistoryData(
item["tag"].ToString(),
dateStuff
));
}
} else if {//Same thing here but item["type"].ToString().Equals("STAY")}
if (Results.Count == 0) Results.Add(new ClanHistoryData("0", DateTime.Now));
} catch (Exception e) {
Results.Add(new ClanHistoryData("-1", DateTime.Now));
}
return Results;
}
Not sure what's going wrong, if it has to do with calling the method from a parallel loop. If the Data is getting messed up in the List. I was thinking since the method is running on different threads there wouldn't be an issue with that.
I get the same number of values but each run they are on a different Identifier, never the same (the identifies don't change)
Upvotes: 0
Views: 276
Reputation: 36586
When doing any parallel processing, things become much easier if data is immutable and methods are pure.
Your LogCheck method uses DateTime.Now
, so it is not pure. Parallel.For is free to run the iterations in any order i wants to, so it is not unexpected that the results will be semi-random.
To fix this you should probably take the dataTime as a parameter to the method, and capture this outside the parallel.for, so it has the same value for all calls. Then the results will probably be identical since you do not seem to use the clashID
parameter.
Upvotes: 0