Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choosing between calling asp.net core blazor methods synchronously or asynchronously

I have a CRUD app in Blazor that simply fetches the assignment lists from a table and has an AssignmentReminderService for data access layer that has a method (async version)

    public async Task<AssignmentReminder> AddAssignment(AssignmentReminder assignment)
    {
        _context.assignments.Add(assignment);
        await _context.SaveChangesAsync();
        return assignment;
    }

I can also call the method with synchromus code as :

    public  AssignmentReminder AddAssignment(AssignmentReminder assignment)
    {
        _context.assignments.Add(assignment);
         _context.SaveChanges();
        return assignment;
    }

Now it is just one database being accessed from a local server(could be hosted on cloud as well) with just one assignment table and the default authentication/authorization tables generated when one uses Individual User Account (aspnetusers, aspnetroles etc) Can someone let me know which of the two ways I should use (between async or sync) method declaration?

like image 459
DeveloperInNeed Avatar asked Dec 19 '25 21:12

DeveloperInNeed


2 Answers

In the general case, you should use asynchronous APIs if they are available. This will result in greater scalability on the server side, since asynchrony will allow the calling request thread to be used for other requests while the asynchronous operation is in progress.

There are specific scenarios where this guideline doesn't apply. E.g., if you're calling a generic asynchronous API (like Stream.ReadAsync) but you know that the implementation is actually synchronous (like MemoryStream). But in general, if there's an asynchronous API, then that's the one you should use.

like image 84
Stephen Cleary Avatar answered Dec 21 '25 22:12

Stephen Cleary


which of the two ways I should use (between async or sync) method declaration?

The first one.

The scarce resource here are the Threads. You want to keep their number down, and the first approach enables that by releasing the Thread to do other work.

In the second approach the Thread is suspended for the duration of the I/O operation. You would need more Threads to handle the same number of requests.

So using async I/O lets the same hardware handle more requests at the same time.

like image 28
Henk Holterman Avatar answered Dec 22 '25 00:12

Henk Holterman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!