为什么等待操作员在调用标记为异步方法的方法时出现错误

333*_*att 0 c# asp.net-web-api

我知道有人问过类似的问题,但是我对此感到茫然。我收到消息:

CS4032“等待”运算符只能在异步方法中使用。考虑使用“异步”修饰符标记该方法,并将其返回类型更改为“任务”。

使用以下代码行:

var something = await _service.GetCurrentSomething(userAuthenticated);
Run Code Online (Sandbox Code Playgroud)

这是方法,标记为异步(正在调用API):

public async Task<Something> GetCurrentSomething(bool isUserLoggedIn)
    {
        var response = _httpClientWrapper.ExecuteGet(
            _insert params here
        ).Result;

        var result = JsonConvert.DeserializeObject<Announcement>(response.ResponseBody);
        return result;
    }
Run Code Online (Sandbox Code Playgroud)

现在,编译器根本没有在抱怨这个方法签名。那么为什么会出现错误消息?我从MVC控制器内部调用它,但是我没有尝试从方法中返回“ something”变量。那么,为什么要引起争议:

changing its return type to 'Task<ActionResult>'
Run Code Online (Sandbox Code Playgroud)

顺便说一句,我已经完成了研究,但还没有一个合适的方法。例如,该方法不是构造函数。

public async Task<ActionResult> Index()
    {

        var healthCheck = _heartbeatService.GetHeartBeat();

        if (healthCheck == null || healthCheck.Result == null || (!healtCheck.Result.Success))
        {
            return View("Error");
        }

        var user = System.Web.HttpContext.Current.User;

        bool userAuthenticated = (user != null) && user.Identity.IsAuthenticated;

        if (userAuthenticated)
        {
            var announcement = await _announcementService.GetCurrentAnnouncement(userAuthenticated);

            var model = CreateAnnouncementViewModel(announcement);

            if (user.IsInRole(Roles.WebAdmin) || user.IsInRole(Roles.Maintenance))
            {
                return RedirectToAction("Index", "AdminGuy");
            }
            if (user.IsInRole(Roles.Shop))
            {
                return RedirectToAction("Index", "Shopguy");
            }
        }

        var viewModel = new LoginViewModel();
        return View("HomePage", viewModel);
    }
Run Code Online (Sandbox Code Playgroud)

JOS*_*Ftw 5

正在执行等待的方法也需要具有async关键字。

因此,这将不起作用:

public Task Hello()
{
    await _service.GetCurrentSomething(userAuthenticated);
}
Run Code Online (Sandbox Code Playgroud)

但这将起作用:

public async Task Hello()
{
    await _service.GetCurrentSomething(userAuthenticated);
}
Run Code Online (Sandbox Code Playgroud)

因此,如果按照您所说的从控制器进行此调用,则需要将async关键字添加到操作方法中,并返回Task<IActionResult>。您也可以将void用于异步内容,但实际上不建议这样做(仅用于事件处理程序等)。

关键字给您的唯一一件事async就是它允许您使用await关键字。除非您以这种方式实际编码(使用异步api,等待...不使用.Result),否则它不会使您的代码异步。