从另一个异步例程调用异步例程

本文关键字:例程 异步 调用 另一个 | 更新日期: 2023-09-27 18:33:23

我认为这是做这种事情的正确方法,但我找不到用这么多词说明这一点的清晰文档。

我有相关的例程,其中例程 A 对其输入进行一些处理,然后委托给例程 B 来完成实际工作。 例如,假设我可以基于整数索引或某个值的字符串键做一些工作。 我可能有两个例程重载,一个获取索引,另一个获取键:

// 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)
}

从另一个异步例程调用异步例程

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

然而,除此之外,效果几乎相同。