How to construct a TransformManyBlock with a delegate
Asked Answered
J

1

6

I'm new to C# TPL and DataFlow and I'm struggling to work out how to implement the TPL DataFlow TransformManyBlock. I'm translating some other code into DataFlow. My (simplified) original code was something like this:

private IEnumerable<byte[]> ExtractFromByteStream(Byte[] byteStream)
{
    yield return byteStream; // Plus operations on the array
}

And in another method I would call it like this:

foreach (byte[] myByteArray in ExtractFromByteStream(byteStream))
{
    // Do stuff with myByteArray
}

I'm trying to create a TransformManyBlock to produce multiple little arrays (actually data packets) that come from the larger input array (actually a binary stream), so both in and out are of type byte[].

I tried what I've put below but I know I've got it wrong. I want to construct this block using the same function as before and to just wrap the TransformManyBlock around it. I got an error "The call is ambiguous..."

var streamTransformManyBlock = new TransformManyBlock<byte[], byte[]>(ExtractFromByteStream);
Jerboa answered 9/11, 2015 at 12:2 Comment(0)
S
7

The compiler has troubles with inferring the types. You need to either specify the delegate type explicitly to disambiguate the call:

var block = new TransformManyBlock<byte[], byte[]>(
    (Func<byte[], IEnumerable<byte[]>>) ExtractFromByteStream);

Or you can use a lambda expression that calls into that method:

var block = new TransformManyBlock<byte[], byte[]>(
    bytes => ExtractFromByteStream(bytes));
Spotter answered 9/11, 2015 at 12:9 Comment(4)
Thank you. This is exactly what I was after. Do you know if one of these methods is preferable over the other?Jerboa
@MattL The first one is slightly more efficient, the second one is slightly more readable. So it's up to you to decide which matters more.Dorotheadorothee
@Dorotheadorothee Efficiency all the way. Thanks very much. For my own learning do you have any links you could share that can explain this further?Jerboa
@MattL There are some explanations in this question.Dorotheadorothee

© 2022 - 2024 — McMap. All rights reserved.