The need for asynchronous code in ASP.NET Core

The first thing to underline is that asynchronous code is not about speed. As mentioned before, asynchronous programming is just about not blocking incoming requests. Therefore, the real benefit is about better vertical scalability, instead of increasing the speed of our code.  For example, let's suppose that our web services perform some I/O operations such as queries on a database: in case we run our code stack in a synchronous way, the thread used by an incoming request will be blocked and not used by any other request until the read or write (I/O operation) process is completed.  By taking an asynchronous approach we are able to release the thread as soon as the read/write operation is executed. Therefore, once the I/O operation is finished, the application will pick up another or the same thread in order to continue the execution of the stack.

The asynchronous code also adds an overhead cost to our system, in fact, it is necessary to add additional logic to coordinate asynchronous operations. For example, let's take a look at the following code:

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
// GET api/values
[HttpGet]
public async Task<ActionResult<string>> Get()
{
return await OperationAsync();
}


public async Task<string> OperationAsync()
{
await Task.Delay(100);
return "Response";
}
}

The aforementioned example defines an action method that calls an asynchronous method. With the help of some external tools, such as ILSpy, it is possible to decompile the C# code and analyze the IL code. The IL code is also known as the intermediate code, which is the code that is generated by the C# compiler and executed at runtime.

The resulting transformation in the IL code of the previously defined Get method looks as follows:

[CompilerGenerated]
private sealed class <Get>d__0 : IAsyncStateMachine
{
// Fields
public int <>1__state;
public AsyncTaskMethodBuilder<ActionResult<string>> <>t__builder;
public ValuesController <>4__this;
private string <>s__1;
private TaskAwaiter<string> <>u__1;

// Methods
public <Get>d__0();
private void MoveNext();
[DebuggerHidden]
private void SetStateMachine(IAsyncStateMachine stateMachine);
}

As you can see, the method has been transformed into a sealed class that implements the IAsyncStateMachine interface. The MoveNext method continuously checks whether the __state of the state machine is changed and updates the result of the operation. All these operations are performed for each asynchronous operation contained in our code.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.46.36