简体   繁体   English

为什么我不能使用wait呢?

[英]Why cant I use await?

I'm working with Identity 2.0 in MVC5, and I'm trying to get the first role for the current user. 我正在使用MVC5中的Identity 2.0,并且正在尝试为当前用户获得第一个角色。

This bit of code doesn't report any errors: 这段代码不报告任何错误:

var DatabaseContext = new ApplicationDbContext();
var thisUserAccount = DatabaseContext.Users.FirstAsync(u => u.Id == Id);

This bit of code: 这段代码:

var DatabaseContext = new ApplicationDbContext();
var thisUserAccount = await DatabaseContext.Users.FirstAsync(u => u.Id == Id);

reports the following error: 报告以下错误:

The 'await' operator can only be used within an async method. “ await”运算符只能在异步方法中使用。 Consider marking this method with the 'async' modifier and changing its return type to 'Task' 考虑使用“异步”修饰符标记此方法,并将其返回类型更改为“任务”

The method is an asynchronous method, so why cant I use "await"? 该方法是异步方法,所以为什么不能使用“ await”?

Also, will calling: 另外,将调用:

DatabaseContext.Users.Load();

before the FirstAsync optimise things a bit (rather than building a ToList which I'm assuming FirstSync does)? 在FirstAsync进行一些优化之前(而不是构建一个我假设FirstSync做的ToList)?

I'm still trying to get to grips with what the async stuff can do, so any useful links will be much appreciated. 我仍在尝试掌握异步内容的功能,因此,非常感谢任何有用的链接。

You need to mark the method that's using await as being async: 您需要将使用await的方法标记为异步:

async Task<UserAccount> DoStuff()
{
 var DatabaseContext = new ApplicationDbContext();
 var thisUserAccount = await DatabaseContext.Users.FirstAsync(u => u.Id == Id);

 return thisUserAccount;
}

That's what the error message is telling you. 这就是错误消息告诉您的内容。

The following characteristics summarize what makes a method async (your missing the first). 以下特征总结了使方法异步的原因(您错过了第一个方法)。

  • The method signature includes an async modifier. 方法签名包括一个异步修饰符。
  • Note: The name of an async method, by convention, ends with an "Async" suffix. 注意:按照惯例,异步方法的名称以“ Async”后缀结尾。
  • The return type is one of the following types: 返回类型是以下类型之一:
    • Task <TResult> if your method has a return statement in which the operand has type TResult. 任务<TResult>如果您的方法有一个返回语句,其中操作数的类型为TResult。
    • Task if your method has no return statement or has a return statement with no operand. 如果您的方法没有return语句或没有操作数的return语句,则执行任务。
    • Void if you're writing an async event handler. 如果您正在编写异步事件处理程序,则该方法无效。

The following link provides a good overview of asynchronous programming using async and await : 以下链接很好地概述了使用asyncawait进行异步编程:
http://msdn.microsoft.com/en-us/library/hh191443.aspx http://msdn.microsoft.com/en-us/library/hh191443.aspx

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

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