Here’s an MWE:
Func<Int32, Boolean> MyFunc = (s) => {
var res = false;
// Insert function logic to modify the value to res
return res;
};
var Result = new List<Int32> ();
var LockObj = new Object ();
ParallelEnumerable.Range (1, 100000)
.ForAll (s => {
if (MyFunc (s)) {
lock (LockObj) { // IS THIS NECESSARY?
Result.Add (s);
} // End lock
}
});
This is what the situation boils down to. Am I correct in thinking I don’t need to lock Result if I am not going to ever query it before the ParallelEnumerable statement has finished executing?
Please note: I know that the MWE is better solved by a “Where” clause, like so:
ParallelEnumerable.Range (1, 100000)
.Where (s => MyFunc (s));
but for reasons not evident in the MWE, this cannot be done.
EDIT
Thank you to everyone who answered. Thanks also for the comments. I have corrected the error spotted by Tung.
Yes, you have to
lock. The Parallel.For will cause concurrent calls toAdd().On a side note:
Will make this a lot more efficient. Less growing also means less contention on the
lock.