异步/等待初学者

本文关键字:初学者 等待 异步 | 更新日期: 2023-09-27 18:35:38

我有一个使用GeoLocator查找用户位置的应用程序。它看起来像这样:

public async (not sure what to put here) Cordinates()
{
    if (_geolocator == null)
    {
        _geolocator = new Geolocator();
    }
    Geoposition _Position = await locator.GetGeopositionAsync();
}

我还有一个字符串属性,我想用它来描述过程。

public string Status {get; set}

例如,当Cordinates()开始时,字符串值应为"正在搜索..."当Cordinates()完成时,它可以说"完成"

我认为这是我应该使用等待/异步的情况,但我可以使用一些帮助来正确处理它。

异步/等待初学者

您应该

将返回类型设置为 Task<T> 如果您返回某些内容或Task如果您不返回任何内容(void)。 例如,如果你有一行像return _position;那么你应该将函数的返回类型设为Task<Geoposition>或者如果你有return 0你应该把它改成Task<int>,如果你只是不返回任何东西或只是return只使用Task

public async Task<your return type> or Task if return type is void Cordinates()
{
    if (_geolocator == null)
    {
        _geolocator = new Geolocator();
    }
    this.Status = "Searching..."; // seting status and awaiting your async GetGeoposition
    Geoposition _Position = await locator.GetGeopositionAsync();
    this.Status = "Done"; // after GetGeoposition is finidshed you are here and setting status to done
}

我认为你应该在使用之前阅读async/await和线程的基础知识。一个好的开始也许是斯蒂芬在这里的帖子。

若要修复代码,它将如下所示(另请参阅 MSDN 以供参考):

public async Task<Geoposition> Cordinates()
{
  if (_geolocator == null)
  {
    _geolocator = new Geolocator();
  }
  Geoposition _Position = await locator.GetGeopositionAsync();
}

Status中,您将检查当前位置是否已被查询。 根据此,返回您选择的字符串值。那里没有异步操作。或者,将雕像设置在等待地理位置之前和之后的位置。