Alnedru
Alnedru

Reputation: 2655

Async methods and await

I have question regarding the way of async programming and await. I understand that when the method is async you can use await to wait for execution of the particular code, but I would like to understand a bit more.

So I have a specific question:

Imagine I have a method:

public async void Starter()
{
    string username = await GetUserNameFromDBAsync();
    bool updated = await UpdateUserTown();
}

public async static Task<string> GetUserNameFromDBAsync()
{
    using(DBContext context = new DBContext())
    {
       return await context.User.FindByIdAsync(currentid).Name;
    }
}

public async static Task<bool> UpdateUserTown()
{
    using(DBContext context = new DBContext())
    {
       User user = await context.User.FindUserByIDAsync(currentid);
       user.Town="New Town";
       try
       {
          context.SaveChangesAsync();
       }
       catch(Exception ex)
       {return false}
       return true;
    }
}

Ok doing this code, although I use everywhere async, but all the time I have to do await ... so basically for performance it will be exactly the same as if I would remove all this asyncs and awaits and do it without ...

Or maybe I miss something?

Upvotes: 1

Views: 187

Answers (1)

Daniel Mann
Daniel Mann

Reputation: 58980

In desktop applications, async isn't about performance, it's about responsiveness. You don't want your application's GUI to freeze up while performing long-running, I/O bound operations. The usual way of accomplishing that is via threading, but threads are expensive and difficult to properly synchronize, and they're overkill if all you want to do is keep your UI responsive while you're pulling down data from a web service.

In web applications, having an async controller lets your website process more requests concurrently, because the thread your controller is running on can go back into the thread pool and serve more requests while it's waiting for your awaits to complete.

Also, a note on your code: You should never have something marked as async void unless it's an event handler. You can't await an async void method, and you can't catch exceptions that occur. Instead, if your method doesn't return anything, use async Task.

Upvotes: 6

Related Questions