简体   繁体   中英

Nesting async/await calls in ASP.NET MVC

I am pretty new to async/await for ASP.NET MVC and have a quick question about it. My question is it necessary to use async/await on nested calls to a database? For instance:

UnitOfWork.cs

public async Task CommitAsync()
{
     await _context.SaveChangesAsync();
}

AccountService.cs

public async Task SaveLoginAttemptAsync(LoginAttempt loginAttempt)
{
     _appContext.Repository<LoginAttempt>().Add(loginAttempt);
     await _appContext.UnitOfWork.CommitAsync();
}

AccountController.cs

//..
var attempt = new LoginAttempt()
{
    Email = User.Identity.GetEmail(),
    Logintime = DateTime.Now,
    Successful = successful ? "Y" : "N",
    IpAddress = Request.UserHostAddress,
    UserId = Convert.ToInt32(User.Identity.GetUserId())
 };
 await _accountService.SaveLoginAttemptAsync(attempt);
//..

Are the async/await methods on SaveLoginAttemptAsync in the AccountService.cs and the code block in AccountController.cs necessary since the end point uses async/await?

Thanks for the help!

Yes, with async/await it's turtles all the way down. Doing otherwise will mess with your debugging experience.

Technically you can skip the await on all the "deeper" returns since you aren't relying on the return value in that context. However, you don't really want to.

If you skip the await and return a Task , then the method won't be in the callstack while you are debugging since it's actually await ing on the Task it returned, not the code in the method itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM