Asynchronous code targets scalability making us use the resources of our servers better.
The inspiration for this article comes from the talk given by
Maarten Balliauw.
What is asynchronous code good for?
Asynchronous programming can in some cases help with performance by parallelizing a task. But, that is not its main benefit in day to day development.
Instead, the main benefit comes from making our code more scalable. The scalability feature of a system relates to how it handles a growing amount of work. And its potential to scale to accommodate that growth.
Soluation
1:We can use horizontal scaling no matter if we have synchronous or asynchronous code. There is no difference.
2:Vertical scaling,Another way of scaling is to improve how many requests our server can handle. Every single request will most likely not perform any better. But, we can increase the number of concurrent requests the server can handle.
Some useful tips:
1: Once the thread is waiting on await, thread will be returned to thread poll.
2:: cancelling the task when one of task throw exception when parallel how handle that
3:; synchronization Context: asp .net have asp .net core doesn’t have
Task.Result() doesn’t deadlock but may block thread .
we don’t need configureAwait(false) is not necessary because there is no synchronization context.
if you think your library might be use by full dotent.
5: we often need to communicate multiple api
using these call parallel.
List tasks = new ListTask ( GetBOOK1Async,GetBOOK2Async)
try
{
return await Task.WhenALL(tasks);
}
catch(operationCanceledException excepation)
{
http client will throw Opertion canceled exception
forearch( var task in tasks
{
logger.Log($”task with task Id: {task.Id} has been canceled”};
}
}
catch(excepation ex)
{
}
cancelationToken: most calls asp .net core that work with task can be canceled.
make sure cancel task manually but ask http client to cancel the task.
var response = await httpclient.GetAsync(bookcoverUrl, cancellationToken);
(rsponse.IsSuccessCode)
{
var bookCover = JsonConverter.DeseralizeObject(
await rersponse.Content.ReadAsync());
return bookcover;
}
_cancellationToken.cancel();
return null;
}
when one of call canceled we should cancel all the task.
Which work should we use async for?
Async is not the solution to all thread blocking code. Threads block if we call a method that performs some heavy computation or if it needs to wait for IO. It is only in the case of IO that we get any gain from using async.
IO bound
Any task that accesses the file system or any external service is good candidates for async.
Computational bound
Any algorithm that takes a long time and is CPU or memory intensive are bad candidates for async.
Examples
Adding an entity using entityframework: IO happens when we call save. Not when we initially add the entity. It is not a good candidate for using async. Entityframework supplies us with an async add method, but we gain nothing from using it.
ASP.NET Example
Asp .net b
3
k