runtime icon indicating copy to clipboard operation
runtime copied to clipboard

TransformBlock's MaxDegreeOfParallelism is not working as expected

Open vishwas-trivedi opened this issue 7 years ago • 9 comments

Problem Definition

I'm trying to execute multiple Async tasks in parallel by using TransformBlock in ASP.NET core API. The problem that I'm facing is if I set MaxDegreeOfParallelism to 1, it executes multiple messages in parallel but as per my understanding it should only execute 1 message at a time because MaxDegreeOfParallelism is set to 1.

My code looks like following :

public static async Task<List<object>> ParallelTaskExecutor(object[] data, Func<object, Task<object>> taskToExecute, int maxDegreeOfParallelism, CancellationToken cancellationToken)
{
    var options = new ExecutionDataflowBlockOptions()
    {
        CancellationToken = cancellationToken,
        MaxDegreeOfParallelism = maxDegreeOfParallelism
    };

    // Append task for parallel execution.
    var workerBlock = new TransformBlock<object, Task<object>>(taskToExecute, options);
    for (var index = 0; index < data.Length; index++)
    {
        workerBlock.Post(new object[] { data[index], options.CancellationToken,});
    }

    // Get result of tasks as it finishes.
    var finalResult = new List<object>();
    for (var i = 0; i < data.Length; i++)
    {
        var result = await workerBlock.Receive().ConfigureAwait(false);
        finalResult.Add(result);
    }

    return finalResult;
}

I tried adding log to check the execution flow and it produced flow as following :

Process start for task: 1
Process start for task: 2
Process start for task: 3
Process start for task: 4

Process end for task: 4
Process end for task: 3
Process end for task: 2
Process end for task: 1

Above log shows that all the tasks are started in parallel and ended in the same sequence. I also tried replacing TransformBlock with ActionBlock just for the sake of confirmation and flow is as following :

Process start for task: 1
Process end for task: 1

Process start for task: 2
Process end for task: 2

Process start for task: 3
Process end for task: 3

Process start for task: 4
Process end for task: 4

which is expected out put because MaxDegreeOfParallelism is set to 1 and thus task 2 should not start before task 1 finishes its job.

Note : Above tasks actually send HTTP request to specific server.

Expected Output Task2 should not start until Task1 ends because MaxDegreeOfParalellism is set to 1, so it sould only execute 1 message at a time. Similar to ActionBlock.

Question Is this expected behavior or is it a bug?

vishwas-trivedi avatar Oct 16 '19 11:10 vishwas-trivedi

Can you share a complete repro? Thanks.

stephentoub avatar Oct 16 '19 12:10 stephentoub

@stephentoub Thanks for the quick response. Sorry but I'm not working on any public repo.

vishwas-trivedi avatar Oct 16 '19 12:10 vishwas-trivedi

@stephentoub I doubt that for some reason TranformBlock is executing messages in LIFO order. Are you aware of any such specification that says all messages are executed as soon as they are posted and then continued in LIFO order?

vishwas-trivedi avatar Oct 16 '19 12:10 vishwas-trivedi

repro, not repo :) I mean an example we can run to see the behavior you describe. You shared a function but not the code invoking it.

stephentoub avatar Oct 16 '19 12:10 stephentoub

@stephentoub

repro, not repo :)

Sorry, my bad.

You shared a function but not the code invoking it.

Sorry but the function invoking it and the function getting executed are both proprietary code but I could give you a rough idea of it.

Arguments are as following :

  1. data : Array of URLs
  2. taskToExecute : An async task that send any HTTP request to a particular URL and returns the response.
  3. MaxDegreeOfParallelism : 1
  4. CancellationToken : CancellationToken.None

The purpose is simple, get a array of URL and make request to all URLs in parallel.

Problem By default, MaxDegreeOfParallelism is set to 1 and in this case(in theory) requests should start and end one by one. But it does not as mentioned in the question.

vishwas-trivedi avatar Oct 16 '19 12:10 vishwas-trivedi

Thank you, but there's a lot of possible ways to interpret a description of code rather than code. Please share a simple console app that demonstrates the behavior you're seeing; we can then discuss whether it's by design or not. It doesn't need to be your actual code, just something that exhibits the same behavior you're concerned about.

stephentoub avatar Oct 16 '19 12:10 stephentoub

@stephentoub Hi, I've created a sample to display the difference in execution flow of ActionBlock and TransformBlock when MaxDegreeOfParallelism is set to 1.

output is as following :

=====Action Block=====
Process start for task: 1
Process end for task: 1
Process start for task: 2
Process end for task: 2
Process start for task: 3
Process end for task: 3
Process start for task: 4
Process end for task: 4
=====Action Block=====

=====Transform Block=====
Process start for task: 1
Process start for task: 2
Process start for task: 3
Process start for task: 4
Process end for task: 4
Process end for task: 2
Process end for task: 3
Process end for task: 1
=====Transform Block=====

Above execution looks like setting MaxDegreeOfParallelism has no effect when using TransformBlock. (It always starts all the task irrespective of MaxDegreeOfParallelism)

Please take a look at the attached sample and let me know if I'm doing something wrong or is this by design. Thank you.

Sample.zip

vishwas-trivedi avatar Oct 17 '19 06:10 vishwas-trivedi

@vishwas-trivedi, thank you for providing the sample.

The issue is in the repro, and specifically in how you're defining the TransformBlock. You're instantiating it as:

new TransformBlock<object, Task<object>>

That means the TOutput type of the result from the operation is Task<object> (rather than object). But that means that, from the block's perspective, there isn't any asynchrony to be tracked here: you're giving it a Func<TInput, TOutput> delegate, that delegate gives you back a TOutput, at which point the operation is completed. It just so happens that the TOutput is a task, but the block doesn't care: it invoked the delegate, got back the TOutput, and it's free to move on to the next item.

What you actually wanted was to instantiate the block with:

new TransformBlock<object, object>

At that point, the delegate you give it is a Func<TInput, Task<TOutput>> (note these are two distinct ctors), and when your delegate gives it back the task, the block then knows to track that returned task's completion.

To see this, in your TransformBlockExecutor function, change L20 from:

var workerBlock = new TransformBlock<object, Task<object>>(taskToExecute, options);

to:

var workerBlock = new TransformBlock<object, object>(taskToExecute, options);

and L30 from:

var result = await workerBlock.Receive().ConfigureAwait(false);

to:

var result = await workerBlock.ReceiveAsync().ConfigureAwait(false);

Hope that helps.

stephentoub avatar Oct 17 '19 13:10 stephentoub

@stephentoub Thank you for saving my a** 💃

vishwas-trivedi avatar Oct 18 '19 05:10 vishwas-trivedi