【问题标题】:The 'await' operator can only be used within an async method'await' 运算符只能在异步方法中使用
【发布时间】:2018-05-19 08:00:42
【问题描述】:

我不清楚为什么在操作实际上被标记为异步时收到此消息。

这是我的测试

public void TestMethod1()
   {

   SvcRestClient client =
            new SvcRestClient(new Uri("http://localhost:44395"),
                new AnonymousCredential());

   var tokenRequest = new TokenRequest
        {
            Username = "myusername",
            Password = "p@ssword1"
        };

   tokenRequest.Validate(); // passes

   var tokenResponse = await client.ApiRequestTokenPostWithHttpMessagesAsync(tokenRequest);  


    }

如果我尝试添加等待,我会收到警告

【问题讨论】:

  • 我们好像漏掉了一些你的方法。我在任何地方都没有看到 await 运算符。
  • 这里可能发生了一些事情,似乎缺少代码,我在您的第二种方法中看不到 return 或等待,您可能也希望让 @ 987654325@ 和 await 从您的第一个方法传播并返回为 async task
  • 糟糕,我已更新以修复粘贴错误。
  • 点击灯泡,它的存在是有原因的......

标签: c# rest async-await


【解决方案1】:

您需要更改测试方法的签名以包含 async 以等待测试中的任务。

public async Task TestMethod1() { // Codes to follow.

【讨论】:

  • 然后更新整个调用链......对于任何使用它的人:不要使用 Wat 或 Result。
猜你喜欢
  • 2023-04-04
  • 1970-01-01
  • 2019-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-02
  • 1970-01-01
相关资源
最近更新 更多