Search code examples
c#asp.net-coreasp.net-core-hosted-services

When AllowSynchronousContinuations option should be used with Channels?


I'm implementing simple background job queue in Asp Net Core app. I've created BackgroundJobQueue which uses BoundedChannel<T> under the hood to enqueue items that will be processed via HostedService. Reading documentation I've stumbled upon ChannelOptions.AllowSynchronousContinuations settings for channel.

The descriptions according to msdn says:

Setting this option to true can provide measurable throughput improvements by avoiding scheduling additional work items. However, it may come at the cost of reduced parallelism, as for example a producer may then be the one to execute work associated with a consumer, and if not done thoughtfully, this can lead to unexpected interactions. The default is false.

I don't quite understand wether setting this option to true in my case is a good choice or not. Can someone explain + provide examples when this option is usefull/useless/harmfull?

Edit

Explanation I got:

According to the official statement, when producer depends on consumer, it waits for consumer's job to be done then starts its work, if you Enable the option, producer experiences more idle time. However, if you Disabled the option, because of parallelism, producer experiences lower idle time.

Isn't enabling option is bad? Since api request will take longer to process because producer will stay idle for a longer time. To clearify what I mean. Let's say I want to enqueue background job in my controller

public async Task<IActionResult> Action()
{
    // some code
   await _backgroundJobQueue(() => ....);
   return Ok();
}

If option is enabled, then producer experiences more idle time so It will take action longer to execute?


Solution

  • You have a Background Queue. Therefore, You are synchronizing operations by using Queuing Jobs. it is better to Enable it because you don not want parallelism and the document claims that "it provides measurable throughput improvements"

    as for example a producer may then be the one to execute work associated with a consumer

    According to the official statement, when producer depends on consumer, it waits for consumer's job to be done then starts its work, if you Enable the option, producer experiences more idle time. However, if you Disabled the option, because of parallelism, producer experiences lower idle time.

    This is what i understood and exemplified