简体   繁体   English

在ASP.NET MVC中嵌套异步/等待调用

[英]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. 我是异步/等待ASP.NET MVC的新手,对此有一个简短的问题。 My question is it necessary to use async/await on nested calls to a database? 我的问题是否有必要在对数据库的嵌套调用中使用async / await? For instance: 例如:

UnitOfWork.cs UnitOfWork.cs

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

AccountService.cs AccountService.cs

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

AccountController.cs 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? 由于端点使用async / await,是否需要AccountService.cs中SaveLoginAttemptAsync上的async / await方法和AccountController.cs中的代码块?

Thanks for the help! 谢谢您的帮助!

Yes, with async/await it's turtles all the way down. 是的,使用async / await可以让乌龟一直降下来。 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. 从技术上讲,您可以跳过所有“更深层”返回的await ,因为您不依赖该上下文中的返回值。 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. 如果跳过等待并返回Task ,则该方法在调试时将不在调用堆栈中,因为它实际上正在await返回的Task上的await ,而不是方法本身的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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