Originally,I am using foreach to do my task.
However, I would like to improve the efficiency of the task.
So, I want to use Parallel.ForEach to do my task.
However, error “Object reference not set to an instance occurred.” happened.
Here’s my code:
System.Threading.Tasks.Parallel.ForEach(items, item =>
{
System.Threading.Tasks.Parallel.ForEach(item.a, amount =>
{
WriteToCsv(file, amount.columna, count);
count++;
});
});
If I used foreach(var item in items) and foreach (amount in item.a), the code works fine.
Did I miss something for the Parallel.ForEach method?
Why would you want to do this in parallel? You are appending values to a file, and that is a serial (i.e., non-parallel) process.
If you just use a regular
foreach, you’ll be fine.