In the previous article, how the Thread Pool works was presented. In this article, we will examine the differences between async and sync methods, what is the difference between these two types, and why we should use async methods. When you write a method in sync and, for example, want to save data, when it reaches the SaveChange method, the current thread is blocked and waits for the SaveChange method to finish, then continues. The thread does not change at all, it is the same as the previous thread, and as the number of requests increases, it may slow down the system due to the blocking of the threads, and it will be the same.

But when you write the same method as async, when it reaches the SaveChange method, the current thread does not wait for the SaveChange operation to finish, but returns to the thread pool and can be used to perform another task, which increases Performance. For example, consider the following code:

[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
    Console.WriteLine("Before DoSomething => " + Thread.CurrentThread.ManagedThreadId);
    var rng = new Random();
    DoSomething().GetAwaiter().GetResult();
    Console.WriteLine("After DoSomething => " + Thread.CurrentThread.ManagedThreadId);
    return Enumerable.Range(1, 5).Select(index => new WeatherForecast
    {
        Date = DateTime.Now.AddDays(index),
        TemperatureC = rng.Next(-20, 55),
        Summary = Summaries[rng.Next(Summaries.Length)]
    })
    .ToArray();
}
private async Task DoSomething()
{
    await Task.Delay(5000);
}

When you enter the Get method, the current ManagedThreadId will be displayed on the console screen. Then enter the DoSomething method and pause for 5 seconds and then the rest is done. Because this method is written in sync, when it reaches Task.Delay, the current thread is blocked and continues to work after 5 seconds, and if you look at the console screen, all ManagedThreadIds are the same. This means that the thread has not changed and can not be used elsewhere. If you run the project and send a request to the Get action, you will see the following output:

Before DoSomething => 10
After DoSomething => 10

The number displayed on your system may be different, but both ManagedThreadIds are the same. But if you write the same method as async, in most cases ManagedThreadId is different from DoSomething method. That is, when it reaches the Task.Delay, the current thread is returned to the Thread pool and after another 5 seconds it receives another Thread from the Thread pool and does the rest. If you run the following code:

[HttpGet("Async")]
public async Task<IEnumerable<WeatherForecast>> Async()
{
    Console.WriteLine("Before DoSomething async => " + Thread.CurrentThread.ManagedThreadId
    var rng = new Random();
    await DoSomething();
    Console.WriteLine("After DoSomething async => " + Thread.CurrentThread.ManagedThreadId)
    return Enumerable.Range(1, 5).Select(index => new WeatherForecast
    {
        Date = DateTime.Now.AddDays(index),
        TemperatureC = rng.Next(-20, 55),
        Summary = Summaries[rng.Next(Summaries.Length)]
    })
    .ToArray();
}
private async Task DoSomething()
{
    await Task.Delay(5000);
}

You receive the following output in the console:

Before DoSomething async => 11
After DoSomething async => 4

In fact, methods written async will increase system performance.

;)

Powered by Froala Editor

Comments