Here is some code I found on the MSDN website.
long[] nums = { 1, 2, 3, 4 };
long total = 0;
Parallel.For<long>(0, nums.Length, () => 0, (j, loop, subtotal) =>
{
subtotal += nums[j];
return subtotal;
}, (x) => Interlocked.Add(ref total, x));
Im wondering if somebody could show me how to modify this code to write the results back to a shared array? Something like below.
My_Class[] localArray;
Parallel.For<My_Class[]>(0, localArray.Length, () => 0, (j, loop, messages) =>
{
List<My_Class> tempList = new List<My_Class>();
My_Class myClass = localArray[j];
foreach (Message msg in myClass.GetListOfMessages())
{
if (msg.getHeader() == "Hello")
{
tempList.add(msg);
}
}
messages = temp.toArray();
return messages;
}, (x) => Interlocked.Add(ref localArray, x));
So you see the example above I have a shared local array which contains objects of type "My_Class". The My_Class
object contains a list of messages of which I want to search to find specific types of message with headers "Hello".
So in the example code I use the parallel for loop to iterate through my custom objects and create a temporary list called "tempList" which I eventually convert to an array and return as a result.
However the code above just doesn't work for arrays, specifically the (x) => Interlocked
line, it doesn't seem to be compatible with merging the results returned by many arrays into one array.
Please can someone assist me.