2014-12-07 66 views
0

我认为这是做这类事情的正确方法,但我无法找到明确的文档,用这么多的单词来说明。从另一个异步例程调用异步例程

我有相关的例程,其中例程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(并且我不调用例程B的await),从而节省了在调用状态机时构建状态机的开销。

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

回答

1

好吧,有一个细微的差别。假设找到该键的代码引发异常。在你的第一个代码中,结果将是一个错误的任务。在你的第二段代码中,异常会立即被抛出给调用者。说实话,哪一个更好取决于你的情况。

但是,除此之外,效果几乎相同。