DeveloperInNeed
DeveloperInNeed

Reputation: 33

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?

Upvotes: 2

Views: 1346

Answers (3)

MeTitus
MeTitus

Reputation: 3428

You should be clear about the version of blazor you're talking about, because using async methods in the client is different from using them in the server version.

Upvotes: 2

Henk Holterman
Henk Holterman

Reputation: 273169

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.

Upvotes: 3

Stephen Cleary
Stephen Cleary

Reputation: 456322

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.

Upvotes: 4

Related Questions