【问题标题】:C#, how to return string as result from Async/Await TaskC#,如何从 Async/Await 任务返回字符串作为结果
【发布时间】:2021-01-12 19:08:18
【问题描述】:

我得到了调用 3rd 方 WCF 服务的异步私有方法,作为回报它得到字符串值。我已将 await 添加到 WCF 调用但出现错误

错误

'string' does not contain a definition for GetAwaiter and no accessible extension method accepting first argument of type string

代码

 private async Task<string> InitializeCall()
    {
        string response = string.Empty;

        response = await eziClient.GetTransactionsAsync(username, "", BatchNumber.ToString(), "").GetAwaiter().GetResult();
        

        return response;
    }

不确定我在这里遗漏了什么?

【问题讨论】:

  • 为什么在async方法中需要GetAwaiter().GetResult()
  • 这个方法不应该是异步的。删除 async 并返回 eziClient.GetTransactionsAsync(username, "", BatchNumber.ToString(), "") 而没有任何响应变量
  • 起初,我很难理解异步编程。但理解它以避免代码异味非常重要。您可以阅读:docs.microsoft.com/en-us/dotnet/csharp/programming-guide/… 以及最佳实践:medium.com/@deep_blue_day/…。避免使用 .Wait() 或 .GetAwaiter().GetResult()!

标签: c#


【解决方案1】:

删除.GetAwaiter().GetResult()

 private async Task<string> InitializeCall()
    {
        string response = string.Empty;

        response = await eziClient.GetTransactionsAsync(username, "", BatchNumber.ToString(), "");
        

        return response;
    }

.GetAwaiter().GetResult() 的结果是string,你不能awaitstring

【讨论】:

  • 谢谢你说得通!...这很有帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-08
  • 1970-01-01
  • 1970-01-01
  • 2019-05-30
  • 2020-02-29
相关资源
最近更新 更多