我有一个使用 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}
例如,当 Colutes()
开始时,字符串值应为“正在搜索...”,而当 Colutes()
完成时,它可能会显示“完成” ”
我认为在这种情况下我应该使用await/async,但我可以使用一些帮助来正确处理它。
最佳答案
您应该将返回类型设置为 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
}
关于c# - 适合初学者的异步/等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27674977/