public unsafe void Test_ParallelHelper_ForEach_In2D( int sizeY, int sizeX, int row, int column, int height, int width) { int[,] data = CreateRandomData2D(sizeY, sizeX); // Create a memory wrapping the random array with the given parameters ReadOnlyMemory2D <int> memory = data.AsMemory2D(row, column, height, width); Assert.AreEqual(memory.Length, height * width); Assert.AreEqual(memory.Height, height); Assert.AreEqual(memory.Width, width); int sum = 0; // Sum all the items in parallel. The Summer type takes a pointer to a target value // and adds values to it in a thread-safe manner (with an interlocked add). ParallelHelper.ForEach(memory, new Summer(&sum)); int expected = 0; // Calculate the sum iteratively as a baseline for comparison foreach (int n in memory.Span) { expected += n; } Assert.AreEqual(sum, expected, $"The sum doesn't match, was {sum} instead of {expected}"); }
public void Test_ParallelHelper_ForEach_Ref2D( int sizeY, int sizeX, int row, int column, int height, int width) { int[,] data = CreateRandomData2D(sizeY, sizeX), copy = (int[, ])data.Clone(); // Prepare the target data iteratively foreach (ref int n in copy.AsSpan2D(row, column, height, width)) { n = unchecked (n * 397); } Memory2D <int> memory = data.AsMemory2D(row, column, height, width); Assert.AreEqual(memory.Length, height * width); Assert.AreEqual(memory.Height, height); Assert.AreEqual(memory.Width, width); // Do the same computation in paralellel, then compare the two arrays ParallelHelper.ForEach(memory, new Multiplier(397)); CollectionAssert.AreEqual(data, copy); }