【问题标题】:Nesting async/await calls in ASP.NET MVC在 ASP.NET MVC 中嵌套 async/await 调用
【发布时间】:2015-11-10 15:47:24
【问题描述】:

我对 ASP.NET MVC 的 async/await 非常陌生,并且有一个关于它的快速问题。我的问题是有必要在对数据库的嵌套调用中使用 async/await 吗?例如:

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);
//..

由于端点使用异步/等待,AccountService.cs 中的 SaveLoginAttemptAsync 和 AccountController.cs 中的代码块是否需要异步/等待方法?

感谢您的帮助!

【问题讨论】:

    标签: c# asp.net asp.net-mvc asynchronous async-await


    【解决方案1】:

    是的,使用 async/await 时,乌龟一直在下降。否则会影响您的调试体验。

    从技术上讲,您可以跳过所有“更深”返回的await,因为您不依赖该上下文中的返回值。但是,您并不想这样做。

    如果您跳过等待并返回Task,那么在您调试时该方法将不在调用堆栈中,因为它实际上是在它返回的任务上awaiting,而不是方法本身的代码。

    【讨论】:

    • 另外,在非 UI 代码(不在控制器中的代码)上,所有等待的任务都应该调用 ConfigureAwait(false)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-04
    • 2020-03-09
    • 2021-08-29
    • 1970-01-01
    • 2015-12-10
    • 2016-06-03
    相关资源
    最近更新 更多