0

I think this is the correct way to do this sort of thing, but I can't find clear documentation that says so in so many words.

I have related routines where RoutineA does some processing on its inputs, then delegates to RoutineB to do the actual work. For example, suppose I can do some work based on either the integer index or the string key of some value. I might have two overloads of some routine, one that takes the index and one that takes the key:

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

Now, suppose RoutineB wants to be async, so it becomes:

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

So... My question is, assuming RoutineA does no asynchronous processing of its own prior to calling RoutineB, can I code it like this. Note that I do NOT mark the routine as async (and I don't await the call to RoutineB), thus saving the overhead of building the state machine when it's called.

// 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)
}
Bob.at.Indigo.Health
  • 11,023
  • 13
  • 64
  • 111

1 Answers1

1

Well, there is a slight difference. Suppose the code that finds the key throws an exception. In your first code, the result would be a faulted task. In your second piece of code, the exception would immediately be thrown to the caller. Which of those is preferable depends on your situation, to be honest.

Other than that, however, the effect is pretty much the same.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194