use Span inside of Parallel.For loop

109 Views Asked by At

I am using Span to cast a float array to a byte array. Using a normal for loop is no problem, but for the amount of numbers I have, I need to parallelize my code, so I ended up using Parallel.For. The problem is that I can't use the Span inside this loop. This is my code:

Span<float> floats = MemoryMarshal.Cast<byte, float>(posColBuffer);
Parallel.For(0, posColBuffer.Length/4, i=>
{

    var scalar = calcScalar(i);
    float color = calcColor(i);

    var id0 = 3 * i;
    for (int j = 0; j < 3; j++)
    {
        floats[i+j] = directions[id0 + j] * scalar;
        floats[colorOffset + i+j] = color;
    }
});

The Error the IDE tells me is "Cannot use local variable 'floats' of byref-like type 'Span' inside lambda expression"

I tried putting the constructing of the Span inside the Parallel.For, but that did not work. It showed no error but it never exited the parallel for loop.

Is it possible to do this?

1

There are 1 best solutions below

2
On BEST ANSWER

Span is stack-only datastructure and by design it is guaranteed to remain on stack and can not leave it. You can move the cast inside the For:

Parallel.For(0, posColBuffer.Length/4, i=>
{
    Span<float> floats = MemoryMarshal.Cast<byte, float>(posColBuffer);
    // ...
});

Note that you also have indexing error for floats[i + j] since it will overflow as mentioned by @Matthew Watson in the comments.