【问题标题】:Calling an async routine from another async routine [duplicate]从另一个异步例程调用异步例程[重复]
【发布时间】:2023-04-04 02:33:01
【问题描述】:

我认为这是做这类事情的正确方法,但我找不到清晰的文档可以用这么多的词来表达。

我有相关的例程,其中 RoutineA 对其输入进行一些处理,然后委托给 RoutineB 执行实际工作。例如,假设我可以根据整数索引或某个值的字符串键做一些工作。我可能有一些例程的两个重载,一个使用索引,一个使用键:

// Do the work based on the int index
public bool RoutineA(int index)
{
    // Find the key
    string key = {some function of index};

    // Let the other overload do the actual work
    return RoutineB(key)
}

// Do the work based on the string key
public bool RoutineB(string key)
{
    bool result = {some function of key};
    return result;
}

现在,假设 RoutineB 想要异步,那么它变成:

// Do the work based on the string key
public async Task<bool> RoutineB(string key)
{
    bool result = await {some function of key};
    return result;
}

所以...我的问题是,假设 RoutineA 在调用 RoutineB 之前没有自己的异步处理,我可以这样编码吗?请注意,我没有将例程标记为async(并且我没有await 调用RoutineB),从而节省了在调用时构建状态机的开销。

// Do the work based on the int index
public Task<bool> RoutineA(int index)
{
    // Find the key
    string key = {some function of index};

    // Let the other overload do the actual work
    return RoutineB(key)
}

【问题讨论】:

    标签: c# asynchronous async-await


    【解决方案1】:

    嗯,有一点不同。假设找到密钥的代码抛出异常。在您的第一个代码中,结果将是一个错误的任务。在您的第二段代码中,异常将立即被抛出给调用者。老实说,哪个更可取取决于您的情况。

    不过,除此之外,效果几乎相同。

    【讨论】:

      猜你喜欢
      • 2020-03-04
      • 1970-01-01
      • 1970-01-01
      • 2022-06-29
      • 2014-09-13
      • 2023-03-18
      • 2018-01-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多