Is this a proper way of using async/await with EF for an API? If not, can you please show me some options? The code is compiling and shows no errors. The application is working fine, but I want to make sure that it runs asynchronous.
public class AdminController : ControllerBase
{
[HttpGet("Users")]
public async Task<IResult> Users()
{
return await Admin.GetUsers();
}
}
public static class Admin
{
internal static async Task<IResult> GetUsers()
{
using var context = new DataBaseContext();
List<User>? _users = context.users.ToList();
return (_users.Count == 0) ?
Results.NotFound() :
Results.Ok(_users);
}
}
Or should I use this instead?
public class AdminController : ControllerBase
{
[HttpGet("Users")]
public Task<IResult> Users()
{
return Admin.GetUsers();
}
}
public static class Admin
{
internal static async Task<IResult> GetUsers()
{
using var context = new DataBaseContext();
List<User>? _users = await context.users.ToListAsync();
return (_users.Count == 0) ?
Results.NotFound() :
Results.Ok(_users);
}
}
CodePudding user response:
The second one is what you want to use. Your first option lacks an async signature meaning you cannot await your static async method. To understand why you must understand what async and await does at runtime. So you have a bunch of threads running in a thread pool and when you have a request come in, a thread gets used to run your code and if its lacking async and await it would run in a synchronous fashion. This means that the thread will be out of that pool until the end of processing. If that admin function took 10 seconds to process, that thread will be locked to that request for 10 seconds. In that same example if you mark it as async and await, your thread goes back into the pool while you await and a callback gets used to say "Hey I'm done" and completes the execution from that await. It becomes more important as your application gets more requests. Hope I explained it well enough