【问题标题】:Can't fix return type on Async无法修复异步的返回类型
【发布时间】:2014-04-04 18:22:06
【问题描述】:

我目前遇到这个问题和这个错误:

  • 问题:我无法弄清楚如何解决我遇到的错误,即使我在 Google 搜索等上阅读了有关它的文档。真的,不要再告诉我这样做了,我不知道不知道怎么做!

  • 错误:异步方法的返回类型必须为 void,Task 或 Task

  • 代码:

private async Geoposition userLocation()
    {
    Geolocator geolocator = new Geolocator();
    geolocator.DesiredAccuracyInMeters = 50;
    try
    {
        Geoposition geoposition = await geolocator.GetGeopositionAsync(maximumAge:TimeSpan.FromMinutes(5),timeout:TimeSpan.FromSeconds(10));
        return geoposition;
    }
    catch (UnauthorizedAccessException)
    {
        return null;
    }
    return null;
}

【问题讨论】:

    标签: c# windows-phone-8 asynchronous geolocation async-await


    【解决方案1】:

    该错误准确地告诉您问题所在。您的方法必须是voidTaskTask<T>

    将您的方法签名更改为:

    private async Task<Geoposition> userLocation() { ... }
    

    【讨论】:

    • 谢谢,我实际上不知道我可以返回这样的值。我不知道那个任务符号:)
    • 我现在不明白的是如何从调用它的函数中读取返回值。我不能只制作一个 Geoposition 位置变量,它告诉我它不能从 Task 转换。你会怎么做?
    • 没关系,我通过以下方式修复它: Geoposition currentPosition = await userLocation();我添加了 await 并且它起作用了:)
    【解决方案2】:

    正如错误试图对您说的那样:您需要将函数的返回类型更改为任务,因此它看起来像这样:

    private async Task<Geoposition> userLocation
    

    【讨论】:

      【解决方案3】:

      当您使用async 时,您应该返回TaskTask&lt;T&gt;void

      private async Task<Geoposition> userLocation()
      {
          //Do something here
      }
      

      你可以查看this documentation关于异步返回类型

      【讨论】:

        猜你喜欢
        • 2019-06-04
        • 2019-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多