Consider the following code:
private static void IncrementList(List<int> items)
{
Enumerable.Range(0, items.Count).AsParallel().ForAll(i =>
{
items[i] += 1;
});
}
Is this "safe"?
I believe it is safe, because there is no adding or removing which would resize the backing array. However, after learning about the volatile
keyword and why it exists, I am wondering if there could be issues with cached cpu values since there is no locking.
var numbers = Enumerable.Range(0, 100).Select(_ => 1).ToList();
IncrementList(numbers);
foreach (var number in numbers) {
Console.WriteLine(number); // could this write a stale "1" value since IncrementList has no locking?
}
The practical usage for this is I have an API where the request supplies a list of Ids, I need to request the resources for each Id (which I would like to do in parallel because each requires a network request), and I need to return the response in the same order as the requested list of Ids.