c# - 适合初学者的异步/等待

标签 c# .net asynchronous async-await

我有一个使用 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/

相关文章:

c# - 异步 MVC Controller 操作方法执行不在 'await' 处等待

c# - 如何验证 SMTP 服务器

c# - 内部路由/代理

c# - 生产中用于 PDF 生成的 LaTeX

android - android中如何进行同步?

javascript - vue js挂载firebase异步调用不更新数据

email - grails 中的异步邮件插件实现

c# - 在并行 for 循环中测试 2 个数组是否相等

c# - 如何访问另一个窗口上的控件

c# - 如何在 C# 中捕获 Shell 命令输出?