Do async and concurrent work with ActionBlock TPL DataFlow in c#

Mohsen Rajabi
2 min readSep 17, 2020

--

In many scenarios in different projects, there are usually a number of things that we want to do in addition to the main work, but the cost of doing them does not affect the main work or the request does not wait to do the work. Let me give you an example:
1- You send a code to the user’s mobile to log in to your service and the user must send that code to you. In the first step, when you want to send a code, you must use an external service to send sms. If you wait for the SMS provider to respond and keep the request open, any external service delay will cause a delay in your system.
2- Save the file or logging
Different programmers use different ways to do this, such as not using the word await. I do not recommend this. Most of the issues that the current request thread may end sooner than your request thread …
Use ActionBlock
There are valuable classes in the TPL library. One of them is ActionBlock. This class is part of the DataFlow class. This class is used to create a process. Not in our discussion, but as far as you can specify a flow that will eventually run Concurrency and Async. With the ActionBlock class, you can specify a task and specify its synchronization settings. After that, you can send your items to that process one by one and without interruption. To do this, you must first define a class that has a Singleton lifetime.

enough talk, show me the code!!!!

When using ActionBlock, you can set Options to control the degree of Async

1- Add Worker class to singleton lifetime. We have set the degree of synchronization to 10 here. This means that at the moment 10 items are sent to the code. The default is degree 1

2- req sms model

3- sms provider

This way you can create a Worker for each task.
But there is a better solution
You can also use the following class that manages ActionBlock

1- Workers class to singleton lifetime

2-How to use

--

--

Mohsen Rajabi

Technical Lead at Mofid Securities .NET Backend Developer / Architect — Consultant